MSDN Visual Basic 6

Download as pdf or txt
Download as pdf or txt
You are on page 1of 728

Product Documentation

All Products | Support | Search | microsoft.com Guide

Visual Basic Home |


Search This Site

Go
Advanced Search

Visual Studio Home


Visual Basic .NET Technical Resources
Visual Basic Home

Product Documentation
Product Information
How to Buy
Technical Resources
Downloads
Support
Community
Visual Basic
Developer Tools
.NET Visual Basic 6.0

Online Documentation

You can find the most recently updated Microsoft Visual Basic® 6.0
documentation in the MSDN® Online Library, including:

Visual Basic Basics


Take a few minutes to get familiar with Visual Basic 6.0.

What's New
Find out about Visual Basic 6.0 features.

Programmer's Guide
Read about Visual Basic programming fundamentals, as well as advanced concepts and
techniques.

Component Tools Guide


Build and use components that interoperate through the Component Object Model (COM).

Enterprise Development
Read about how to develop business-critical distributed applications using Visual Basic.

Data Access Guide


Get the details on data-access programming in Visual Basic.

Reference
Find what you need in the Language Reference, or look up information on controls, wizards
and add-ins, trappable errors, and more.

Samples
Download the Visual Basic samples from the MSDN Online Library.

Printed Documentation

http://msdn.microsoft.com/vbasic/techinfo/documentation/vb6.asp (1 of 2) [11/17/2002 10:30:15 PM]


Product Documentation

Microsoft Visual Basic 6.0 Programmer's Guide


This essential guide is identical in content to the Programmer's Guide available in the online
documentation, and is available in printed form only from Microsoft Press. It offers amply
illustrated how-to information and documentation.

Microsoft Visual Basic 6.0 Reference Library


The three-volume Visual Basic 6.0 Reference Library is the printed reference documentation
for Visual Basic 6.0. In its printed form, the reference library is portable, easy to use, and
easy to browse.

Microsoft Visual Studio Core Reference Set


This five-volume set includes the Microsoft Visual Basic® 6.0 Programmer's Guide, the
Microsoft Visual C++ 6.0 Programmer's Guide, the Microsoft Visual FoxPro® 6.0
Programmer's Guide, the Microsoft Visual InterDev® 6.0 Programmer's Guide, and the
Microsoft Visual J++® 6.0 Programmer's Guide.

MSDN Online
Visit MSDN Online for a list of other books for developers.

Contact Us

© 2002 Microsoft Corporation. All rights reserved. Terms of Use. Privacy Statement Accessibility

http://msdn.microsoft.com/vbasic/techinfo/documentation/vb6.asp (2 of 2) [11/17/2002 10:30:15 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions)

MSDN Library GO
Advanced Search Visual Basic Concepts

Visual Basic Basics

Many of the things that you can do with Visual Basic really aren’t very basic at all. The Visual Basic language is quite powerful — if you can imagine a programming task, it can probably be
accomplished using Visual Basic. As you might guess, there’s a lot to be learned before you can consider yourself a guru; but once you understand the basics of Visual Basic you’ll find that you
are productive in no time at all.

Up One Level
Introducing Visual Basic The first five chapters of the Visual Basic Programmer’s Guide cover the basics, providing the foundation that you will need for anything you want to do in Visual Basic.

Developing an Application in Visual Basic


Forms, Controls, and Menus Chapters

Managing Projects Introducing Visual Basic

Programming Fundamentals
Explains how to install Visual Basic and get assistance while you work.

Developing an Application in Visual Basic

An introduction to the integrated development environment and the process of creating your first application.

Forms, Controls, and Menus

An introduction to the objects that you can put together to create an application.

Managing Projects

An introduction to the tools used to organize your work in Visual Basic.

Programming Fundamentals

An introduction to the nuts and bolts of the Visual Basic language.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconpart1visualbasicbasics.asp (1 of 2) [11/17/2002 10:30:25 PM]


Welcome to the MSDN Library

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconpart1visualbasicbasics.asp (2 of 2) [11/17/2002 10:30:25 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics

MSDN Library GO
Advanced Search Visual Basic Concepts

Introducing Visual Basic

See Also

Up One Level This chapter contains information on installing Microsoft Visual Basic on your system, adding or removing Visual Basic components, and resources for learning or getting additional help with
Visual Basic.
Welcome to Visual Basic
Installing Visual Basic Topics
Getting Assistance While You Work
Welcome to Visual Basic

A brief introduction.

Installing Visual Basic

Instructions for installing Visual Basic.

Getting Assistance While You Work

A discussion of the user assistance model.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconintroducingvisualbasic50.asp [11/17/2002 10:30:31 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Installing Visual Basic

See Also

Up One Level You install Visual Basic on your computer using the Setup program. The Setup program installs Visual Basic and other product components from the CD-ROM to your hard disc. It also installs
the files necessary to view the documentation on the Microsoft Developer Network CD. If you choose, you can install only the Visual Basic documentation and samples to your machine.
Before You Run Setup
Setting Up Visual Basic Important You cannot simply copy files from the CD-ROM to your hard disc and run Visual Basic. You must use the Setup program, which decompresses and installs the files in the
appropriate directories.

● Before You Run Setup Things to check prior to installation.

● Setting Up Visual Basic Instructions for installing Visual Basic.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconinstallingvisualbasic.asp [11/17/2002 10:30:35 PM]


Setting Up Visual Basic

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Installing Visual Basic

Visual Basic Concepts

Setting Up Visual Basic

See Also

When you run the Setup program, a directory is created for Visual Basic; you can then select the components of Visual Basic that you want to install.

With the exception of the operating system files in the \Os directory, files on the compact disc are not compressed, so they're usable directly from the disc. For example, there are numerous tools
and components in the \Tools directory that can be run or installed directly from the CD-ROM.

To set up from compact disc

1. Insert the compact disc in the CD-ROM drive.

2. Use the appropriate command in your operating environment to run the Setup program, which is available in the root directory on Disk 1. If AutoPlay is enabled on your system, the Setup program will automatically load when you insert the compact disc.

3. Select Install Visual Basic 6.0.

4. Follow the setup instructions on the screen.

For More Information See the Readme file for detailed instructions on installing Visual Basic.

Adding or Removing Components of Visual Basic

You can run Setup as many times as necessary. For example, you can run Setup to reinstall Visual Basic in another directory, or to install other portions of Visual Basic.

To add or remove components of Visual Basic

1. Insert the compact disc in the CD-ROM drive.

2. Use the appropriate command in your operating environment to run the Setup program, which is available in the root directory on the compact disc. If AutoPlay is enabled on your system, the Setup program will automatically load when you insert the compact
disc.

3. Select the Custom button in the Microsoft Visual Basic 6.0 Setup dialog box.

4. Select the components to be installed (or deselect the components to be removed) in the Options list box of the Custom dialog box.

5. Follow the setup instructions on the screen.

Starting Visual Basic

Once you have completed the Setup procedure, you can start Visual Basic by using the Start button on the Windows task bar. If AutoPlay is enabled on your system, you can also start Visual Basic
by inserting the Visual Basic compact disc.

For More information See "Developing an Application in Visual Basic."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconsettingupvisualbasic.asp?frame=true [11/17/2002 10:30:37 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Installing Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Setting Up Visual Basic

See Also

Up One Level When you run the Setup program, a directory is created for Visual Basic; you can then select the components of Visual Basic that you want to install.

Before You Run Setup


Setting Up Visual Basic With the exception of the operating system files in the \Os directory, files on the compact disc are not compressed, so they're usable directly from the disc. For example, there are numerous
tools and components in the \Tools directory that can be run or installed directly from the CD-ROM.

To set up from compact disc

1. Insert the compact disc in the CD-ROM drive.

2. Use the appropriate command in your operating environment to run the Setup program, which is available in the root directory on Disk 1. If AutoPlay is enabled on your system, the Setup program will automatically load when you insert the compact disc.

3. Select Install Visual Basic 6.0.

4. Follow the setup instructions on the screen.

For More Information See the Readme file for detailed instructions on installing Visual Basic.

Adding or Removing Components of Visual Basic

You can run Setup as many times as necessary. For example, you can run Setup to reinstall Visual Basic in another directory, or to install other portions of Visual Basic.

To add or remove components of Visual Basic

1. Insert the compact disc in the CD-ROM drive.

2. Use the appropriate command in your operating environment to run the Setup program, which is available in the root directory on the compact disc. If AutoPlay is enabled on your system, the Setup program will automatically load when you insert the compact
disc.

3. Select the Custom button in the Microsoft Visual Basic 6.0 Setup dialog box.

4. Select the components to be installed (or deselect the components to be removed) in the Options list box of the Custom dialog box.

5. Follow the setup instructions on the screen.

Starting Visual Basic

Once you have completed the Setup procedure, you can start Visual Basic by using the Start button on the Windows task bar. If AutoPlay is enabled on your system, you can also start Visual
Basic by inserting the Visual Basic compact disc.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconsettingupvisualbasic.asp (1 of 2) [11/17/2002 10:30:39 PM]


Welcome to the MSDN Library
For More information See "Developing an Application in Visual Basic."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconsettingupvisualbasic.asp (2 of 2) [11/17/2002 10:30:39 PM]


Before You Run Setup

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Installing Visual Basic

Visual Basic Concepts

Before You Run Setup

See Also

Before you install Visual Basic, make sure that your computer meets the minimum requirements, and read the Readme file, located at the root directory on your installation disc.

Check the Hardware and System Requirements

To run Visual Basic, you must have certain hardware and software installed on your computer. The system requirements include:

● Microsoft Windows 95 or later, or Microsoft Windows NT Workstation 4.0 (Service Pack 3 recommended) or later.

● 486DX/66 MHz or higher processor (Pentium or higher processor recommended), or any Alpha processor running Microsoft Windows NT Workstation.

● A CD-ROM disc drive.

● VGA or higher-resolution screen supported by Microsoft Windows.

● 16 MB of RAM for Windows 95/98, 32 MB of RAM for Windows NT Workstation.

● A mouse or other suitable pointing device.

For More Information For more details about requirements, see "System Requirements for Visual Basic" in "Visual Basic Specifications, Limitations, and File Formats."

Read the Readme File

The Readme file lists any changes to the Visual Basic documentation since its publication. It can be found by selecting Read Me First from the initial setup screen, or in the root directory of the CD-
ROM. It can also be accessed from the Visual Basic Start Page in the documentation. Check the first section of the file for details and new information about installing Visual Basic.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconbeforeyourunsetup.asp?frame=true [11/17/2002 10:30:46 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Installing Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Before You Run Setup

See Also

Up One Level Before you install Visual Basic, make sure that your computer meets the minimum requirements, and read the Readme file, located at the root directory on your installation disc.

Before You Run Setup


Setting Up Visual Basic Check the Hardware and System Requirements

To run Visual Basic, you must have certain hardware and software installed on your computer. The system requirements include:

● Microsoft Windows 95 or later, or Microsoft Windows NT Workstation 4.0 (Service Pack 3 recommended) or later.

● 486DX/66 MHz or higher processor (Pentium or higher processor recommended), or any Alpha processor running Microsoft Windows NT Workstation.

● A CD-ROM disc drive.

● VGA or higher-resolution screen supported by Microsoft Windows.

● 16 MB of RAM for Windows 95/98, 32 MB of RAM for Windows NT Workstation.

● A mouse or other suitable pointing device.

For More Information For more details about requirements, see "System Requirements for Visual Basic" in "Visual Basic Specifications, Limitations, and File Formats."

Read the Readme File

The Readme file lists any changes to the Visual Basic documentation since its publication. It can be found by selecting Read Me First from the initial setup screen, or in the root directory of the
CD-ROM. It can also be accessed from the Visual Basic Start Page in the documentation. Check the first section of the file for details and new information about installing Visual Basic.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconbeforeyourunsetup.asp [11/17/2002 10:30:48 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Getting Assistance While You Work

See Also

Up One Level The online documentation system references nearly all aspects of Visual Basic. It includes:

Context-Sensitive Help
Running Code Examples from Help ●


All of the Visual Basic books, providing conceptual information on using the multitude of features in Visual Basic.

Language Reference, containing extensive information on the Visual Basic programming environment and language.

Visual Basic Online Links ● Visual Basic online links, providing pointers to sources of Visual Basic information on the web.

Microsoft Product Support Services ● Microsoft Product Support Services, with information on obtaining technical support.

Note You can view the documentation from the MSDN CDs (you must go through the MSDN installation process) or you can custom install the Visual Basic documents and samples to your
machine during MSDN installation.

Getting the Most Out of Help Content

Help content includes several features designed to make finding information easier.

● What's New in Visual Basic 6.0?

Use this section to go quickly to information on new and enhanced features of Visual Basic. Organized by feature category, it provides close to 200 described links to more information.

● Find It Fast

Use this section to sort out subject areas covered throughout the documentation. Debugging information, for example, comes in a variety of flavors, depending on the kind of project you're working on. The described links in this section make the search
easier.

● Overview topics

Use these to get information about topics in a book or chapter before you go to the topics themselves. By providing a glimpse of content in each topic, the described links in overviews at the head of books, parts, and chapters save time.

● See Also links

Click the See Also link under the topic title to view the titles of topics you can go to for more or related information.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcongettingassistancewhileyouwork.asp [11/17/2002 10:30:57 PM]


Context-Sensitive Help

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Getting Assistance While You Work

Visual Basic Concepts

Context-Sensitive Help

See Also

Many parts of Visual Basic are context sensitive. Context sensitive means you can get help on these parts directly without having to go through the Help menu. For example, to get Help on any
keyword in the Visual Basic language, place the insertion point on that keyword in the Code window and press F1.

You can press F1 from any context-sensitive part of the Visual Basic interface to display Help information about that part. The context-sensitive parts are:

● Every window in Visual Basic (Properties window, Code window, and so on)

● Controls in the Toolbox

● Objects on a form or document object

● Properties in the Properties window

● Visual Basic keywords (statements, functions, properties, methods, events, and special objects)

● Error messages

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconcontextsensitivehelp.asp?frame=true [11/17/2002 10:31:01 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Getting Assistance While You Work

MSDN Library GO
Advanced Search Visual Basic Concepts

Context-Sensitive Help

See Also

Up One Level Many parts of Visual Basic are context sensitive. Context sensitive means you can get help on these parts directly without having to go through the Help menu. For example, to get Help on any
keyword in the Visual Basic language, place the insertion point on that keyword in the Code window and press F1.
Context-Sensitive Help
Running Code Examples from Help You can press F1 from any context-sensitive part of the Visual Basic interface to display Help information about that part. The context-sensitive parts are:
Visual Basic Online Links
Microsoft Product Support Services ● Every window in Visual Basic (Properties window, Code window, and so on)

● Controls in the Toolbox

● Objects on a form or document object

● Properties in the Properties window

● Visual Basic keywords (statements, functions, properties, methods, events, and special objects)

● Error messages

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcontextsensitivehelp.asp [11/17/2002 10:31:03 PM]


Running Code Examples from Help

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Getting Assistance While You Work

Visual Basic Concepts

Running Code Examples from Help

See Also

Many of the language topics in Help contain code examples that you can run from Visual Basic. The following procedures show you how to copy and run a code example from Help.

Note The following procedure is for code examples that do not contain public declarations.

To copy a code example from Help

1. Create a new form by choosing Add Form from the Project menu, or use an existing form. (For more information on creating and using forms, see "Developing An Application in Visual Basic.")

2. Choose Index from the Help menu.

3. In Help, search for graphics, and go to the topic called "FillColor Property."

4. In the FillColor Property topic, click the Example jump, located in the nonscrolling region near the top of the window. (A jump is a word that you can click to go to another topic. Jumps are underlined and the jump text is colored.)

Select the Sub portion of the example. Note that the first "Sub" marks the beginning of the procedure and the last "End Sub" marks the end of the procedure.

5. Right-click the selected text and select Copy from the context menu. The text is copied onto the Clipboard.

6. Return to the form you created and double-click the form to display the Code window.

7. Place the insertion point below any existing code in the Code window.

8. From the Edit menu, choose Paste. The example now appears in the Code window.

9. From the Run menu, choose Start, or press F5.

10. Click the form to run the example code.

Note Some code examples require you to draw controls on the form. For more information on drawing controls, see "Forms, Controls, and Menus."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconrunningcodeexamplesfromhelp.asp?frame=true [11/17/2002 10:31:09 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Getting Assistance While You Work

MSDN Library GO
Advanced Search Visual Basic Concepts

Running Code Examples from Help

See Also

Up One Level Many of the language topics in Help contain code examples that you can run from Visual Basic. The following procedures show you how to copy and run a code example from Help.

Context-Sensitive Help
Running Code Examples from Help Note The following procedure is for code examples that do not contain public declarations.

Visual Basic Online Links


Microsoft Product Support Services To copy a code example from Help

1. Create a new form by choosing Add Form from the Project menu, or use an existing form. (For more information on creating and using forms, see "Developing An Application in Visual Basic.")

2. Choose Index from the Help menu.

3. In Help, search for graphics, and go to the topic called "FillColor Property."

4. In the FillColor Property topic, click the Example jump, located in the nonscrolling region near the top of the window. (A jump is a word that you can click to go to another topic. Jumps are underlined and the jump text is colored.)

Select the Sub portion of the example. Note that the first "Sub" marks the beginning of the procedure and the last "End Sub" marks the end of the procedure.

5. Right-click the selected text and select Copy from the context menu. The text is copied onto the Clipboard.

6. Return to the form you created and double-click the form to display the Code window.

7. Place the insertion point below any existing code in the Code window.

8. From the Edit menu, choose Paste. The example now appears in the Code window.

9. From the Run menu, choose Start, or press F5.

10. Click the form to run the example code.

Note Some code examples require you to draw controls on the form. For more information on drawing controls, see "Forms, Controls, and Menus."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconrunningcodeexamplesfromhelp.asp [11/17/2002 10:31:11 PM]


Visual Basic Online Links

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Getting Assistance While You Work

Visual Basic Concepts

Visual Basic Online Links

See Also

If you have a modem or other means of access, additional information about Visual Basic is available on the web.

Microsoft Web Site

Microsoft's web site contains several areas of interest to Visual Basic programmers. The Visual Basic home page is located at http://www.microsoft.com/vbasic/. Information available at this site
includes:

● Updates on new features, product releases, related products, seminars and special events.

● Additional information on Visual Basic features, including white papers, tips and tutorials, and training resources.

● New product downloads including updates to program files, help updates, drivers, and other Visual Basic related files.

Tip The Visual Basic web site also contains a special Owner’s Area for registered owners that contains many free samples, components, tools, and much more. Why not go to
http://www.microsoft.com/vbasic/owners/ and register your copy of Visual Basic right now?

To access the Microsoft Visual Basic Web site

1. Choose Microsoft on the Web from the Help menu.

2. Select the appropriate option from the submenus.

Note You must have a Web browser installed and you must be connected to the Internet for these options to work. Some of the content on the Microsoft Web site is optimized for Microsoft Internet Explorer and may not be fully visible to other browsers. You can
download the latest version of Internet Explorer from the Web site.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconvisualbasiconlinelinks.asp?frame=true [11/17/2002 10:31:16 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Getting Assistance While You Work

MSDN Library GO
Advanced Search Visual Basic Concepts

Visual Basic Online Links

See Also

Up One Level If you have a modem or other means of access, additional information about Visual Basic is available on the web.

Context-Sensitive Help
Running Code Examples from Help Microsoft Web Site

Visual Basic Online Links


Microsoft's web site contains several areas of interest to Visual Basic programmers. The Visual Basic home page is located at http://www.microsoft.com/vbasic/. Information available at this
Microsoft Product Support Services site includes:

● Updates on new features, product releases, related products, seminars and special events.

● Additional information on Visual Basic features, including white papers, tips and tutorials, and training resources.

● New product downloads including updates to program files, help updates, drivers, and other Visual Basic related files.

Tip The Visual Basic web site also contains a special Owner’s Area for registered owners that contains many free samples, components, tools, and much more. Why not go to
http://www.microsoft.com/vbasic/owners/ and register your copy of Visual Basic right now?

To access the Microsoft Visual Basic Web site

1. Choose Microsoft on the Web from the Help menu.

2. Select the appropriate option from the submenus.

Note You must have a Web browser installed and you must be connected to the Internet for these options to work. Some of the content on the Microsoft Web site is optimized for Microsoft Internet Explorer and may not be fully visible to other browsers. You
can download the latest version of Internet Explorer from the Web site.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconvisualbasiconlinelinks.asp [11/17/2002 10:31:17 PM]


Microsoft Product Support Services

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Getting Assistance While You Work

Visual Basic Concepts

Microsoft Product Support Services

See Also

Microsoft offers a variety of support options to help you get the most from Visual Basic.

If you have a question about the product, first look in the online documentation. If you can't find the answer, contact Microsoft Product Support Services.

Support services are available both within the United States and through subsidiary offices worldwide. For complete details, see Technical Support under the Visual Basic Help menu.

Tell Us What You Think

Microsoft is committed to providing the best possible products to our customers. With each new version, Visual Basic has evolved in order to meet the changing needs of Windows programmers.

We're always interested in hearing from our customers. If you have any suggestions or comments regarding improvements or features that you would like to see in future versions of Visual Basic,
let us know. You can send your suggestions via e-mail to vbwish@microsoft.com, or by calling (425) 936-WISH.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconmicrosoftproductsupportservices.asp?frame=true [11/17/2002 10:31:23 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Getting Assistance While You Work

MSDN Library GO
Advanced Search Visual Basic Concepts

Microsoft Product Support Services

See Also

Up One Level Microsoft offers a variety of support options to help you get the most from Visual Basic.

Context-Sensitive Help
Running Code Examples from Help If you have a question about the product, first look in the online documentation. If you can't find the answer, contact Microsoft Product Support Services.

Visual Basic Online Links


Microsoft Product Support Services Support services are available both within the United States and through subsidiary offices worldwide. For complete details, see Technical Support under the Visual Basic Help menu.

Tell Us What You Think

Microsoft is committed to providing the best possible products to our customers. With each new version, Visual Basic has evolved in order to meet the changing needs of Windows
programmers.

We're always interested in hearing from our customers. If you have any suggestions or comments regarding improvements or features that you would like to see in future versions of Visual
Basic, let us know. You can send your suggestions via e-mail to vbwish@microsoft.com, or by calling (425) 936-WISH.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconmicrosoftproductsupportservices.asp [11/17/2002 10:31:25 PM]


Welcome to Visual Basic

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic

Visual Basic Concepts

Welcome to Visual Basic

See Also

Welcome to Microsoft Visual Basic, the fastest and easiest way to create applications for Microsoft Windows®. Whether you are an experienced professional or brand new to Windows programming,
Visual Basic provides you with a complete set of tools to simplify rapid application development.

So what is Visual Basic? The "Visual" part refers to the method used to create the graphical user interface (GUI). Rather than writing numerous lines of code to describe the appearance and
location of interface elements, you simply add prebuilt objects into place on screen. If you've ever used a drawing program such as Paint, you already have most of the skills necessary to create an
effective user interface.

The "Basic" part refers to the BASIC (Beginners All-Purpose Symbolic Instruction Code) language, a language used by more programmers than any other language in the history of computing.
Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions, and keywords, many of which relate directly to the Windows GUI. Beginners
can create useful applications by learning just a few of the keywords, yet the power of the language allows professionals to accomplish anything that can be accomplished using any other Windows
programming language.

The Visual Basic programming language is not unique to Visual Basic. The Visual Basic programming system, Applications Edition included in Microsoft Excel, Microsoft Access, and many other
Windows applications uses the same language. The Visual Basic Scripting Edition (VBScript) is a widely used scripting language and a subset of the Visual Basic language. The investment you
make in learning Visual Basic will carry over to these other areas.

Whether your goal is to create a small utility for yourself or your work group, a large enterprise-wide system, or even distributed applications spanning the globe via the Internet, Visual Basic has
the tools you need.

● Data access features allow you to create databases, front-end applications, and scalable server-side components for most popular database formats, including Microsoft SQL Server and other enterprise-level databases.

● ActiveX™ technologies allow you to use the functionality provided by other applications, such as Microsoft Word word processor, Microsoft Excel spreadsheet, and other Windows applications. You can even automate applications and objects created using the
Professional or Enterprise editions of Visual Basic.

● Internet capabilities make it easy to provide access to documents and applications across the Internet or intranet from within your application, or to create Internet server applications.

● Your finished application is a true .exe file that uses a Visual Basic Virtual Machine that you can freely distribute.

Visual Basic Editions

Visual Basic is available in three versions, each geared to meet a specific set of development requirements.

● The Visual Basic Learning edition allows programmers to easily create powerful applications for Microsoft Windows and Windows NT®. It includes all intrinsic controls, plus grid, tab, and data-bound controls. Documentation provided with this edition includes the
Learn VB Now CD plus the Microsoft Developer Network (MSDN™) Library CDs containing full online documentation.

● The Professional edition provides computer professionals with a full-featured set of tools for developing solutions for others. It includes all the features of the Learning edition, plus additional ActiveX controls, the Internet Information Server Application Designer,
integrated Visual Database Tools and Data Environment, Active Data Objects, and the Dynamic HTML Page Designer. Documentation provided with the Professional edition includes the Visual Studio Professional Features book plus Microsoft Developer Network CDs
containing full online documentation.

● The Enterprise edition allows professionals to create robust distributed applications in a team setting. It includes all the features of the Professional edition, plus Back Office tools such as SQL Server, Microsoft Transaction Server, Internet Information Server, Visual
SourceSafe, SNA Server, and more. Printed documentation provided with the Enterprise edition includes the Visual Studio Enterprise Features book plus Microsoft Developer Network CDs containing full online documentation.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconwelcometovisualbasic.asp?frame=true [11/17/2002 10:31:35 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Welcome to Visual Basic

See Also

Up One Level Welcome to Microsoft Visual Basic, the fastest and easiest way to create applications for Microsoft Windows®. Whether you are an experienced professional or brand new to Windows
programming, Visual Basic provides you with a complete set of tools to simplify rapid application development.
Welcome to Visual Basic
Installing Visual Basic
So what is Visual Basic? The "Visual" part refers to the method used to create the graphical user interface (GUI). Rather than writing numerous lines of code to describe the appearance and
Getting Assistance While You Work location of interface elements, you simply add prebuilt objects into place on screen. If you've ever used a drawing program such as Paint, you already have most of the skills necessary to
create an effective user interface.

The "Basic" part refers to the BASIC (Beginners All-Purpose Symbolic Instruction Code) language, a language used by more programmers than any other language in the history of computing.
Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions, and keywords, many of which relate directly to the Windows GUI. Beginners
can create useful applications by learning just a few of the keywords, yet the power of the language allows professionals to accomplish anything that can be accomplished using any other
Windows programming language.

The Visual Basic programming language is not unique to Visual Basic. The Visual Basic programming system, Applications Edition included in Microsoft Excel, Microsoft Access, and many other
Windows applications uses the same language. The Visual Basic Scripting Edition (VBScript) is a widely used scripting language and a subset of the Visual Basic language. The investment you
make in learning Visual Basic will carry over to these other areas.

Whether your goal is to create a small utility for yourself or your work group, a large enterprise-wide system, or even distributed applications spanning the globe via the Internet, Visual Basic
has the tools you need.

● Data access features allow you to create databases, front-end applications, and scalable server-side components for most popular database formats, including Microsoft SQL Server and other enterprise-level databases.

● ActiveX™ technologies allow you to use the functionality provided by other applications, such as Microsoft Word word processor, Microsoft Excel spreadsheet, and other Windows applications. You can even automate applications and objects created using the
Professional or Enterprise editions of Visual Basic.

● Internet capabilities make it easy to provide access to documents and applications across the Internet or intranet from within your application, or to create Internet server applications.

● Your finished application is a true .exe file that uses a Visual Basic Virtual Machine that you can freely distribute.

Visual Basic Editions

Visual Basic is available in three versions, each geared to meet a specific set of development requirements.

● The Visual Basic Learning edition allows programmers to easily create powerful applications for Microsoft Windows and Windows NT®. It includes all intrinsic controls, plus grid, tab, and data-bound controls. Documentation provided with this edition includes
the Learn VB Now CD plus the Microsoft Developer Network (MSDN™) Library CDs containing full online documentation.

● The Professional edition provides computer professionals with a full-featured set of tools for developing solutions for others. It includes all the features of the Learning edition, plus additional ActiveX controls, the Internet Information Server Application
Designer, integrated Visual Database Tools and Data Environment, Active Data Objects, and the Dynamic HTML Page Designer. Documentation provided with the Professional edition includes the Visual Studio Professional Features book plus Microsoft
Developer Network CDs containing full online documentation.

● The Enterprise edition allows professionals to create robust distributed applications in a team setting. It includes all the features of the Professional edition, plus Back Office tools such as SQL Server, Microsoft Transaction Server, Internet Information Server,
Visual SourceSafe, SNA Server, and more. Printed documentation provided with the Enterprise edition includes the Visual Studio Enterprise Features book plus Microsoft Developer Network CDs containing full online documentation.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconwelcometovisualbasic.asp (1 of 2) [11/17/2002 10:31:36 PM]


Welcome to the MSDN Library

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconwelcometovisualbasic.asp (2 of 2) [11/17/2002 10:31:36 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics

MSDN Library GO
Advanced Search Visual Basic Concepts

Developing an Application in Visual Basic

See Also

Up One Level It takes just a few minutes to build your first Visual Basic application. You create the user interface by "drawing" controls, such as text boxes and command buttons, on a form. Next, you set
properties for the form and controls to specify such values as captions, color, and size. Finally, you write code to bring the application to life. The basic steps you take in creating your first
Visual Basic Concepts application will show you principles that you'll use with every other application you develop.

Elements of the Integrated Development Environment


Your First Visual Basic Application This chapter provides an overview of the application development process, describes the terms and skills you need to use Visual Basic, and takes you step by step through several simple
applications.

Topics

Visual Basic Concepts

A comparison of Visual Basic and traditional programming languages.

Elements of the Integrated Development Environment

An introduction to the Visual Basic environment and tools.

Your First Visual Basic Application

Step-by-step creation of a simple application, illustrating basic techniques.

Sample application

Firstapp.vbp

Some of the code examples in this chapter are taken from the Firstapp.vbp sample application which is listed in the Samples directory.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondevelopingapplicationinvisualbasic.asp [11/17/2002 10:32:17 PM]


Visual Basic Concepts

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic

Visual Basic Concepts

Visual Basic Concepts

See Also

In order to understand the application development process, it is helpful to understand some of the key concepts upon which Visual Basic is built. Because Visual Basic is a Windows development
language, some familiarity with the Windows environment is necessary. If you are new to Windows programming, you need to be aware of some fundamental differences between programming for
Windows versus other environments.

How Windows Works: Windows, Events and Messages

A complete discussion of the inner workings of Windows would require an entire book. A deep understanding of all of the technical details isn't necessary. A simplified version of the workings of
Windows involves three key concepts: windows, events and messages.

Think of a window as simply a rectangular region with its own boundaries. You are probably already aware of several different types of windows: an Explorer window in Windows, a document
window within your word processing program, or a dialog box that pops up to remind you of an appointment. While these are the most common examples, there are actually many other types of
windows. A command button is a window. Icons, text boxes, option buttons and menu bars are all windows.

The Microsoft Windows operating system manages all of these many windows by assigning each one a unique id number (window handle or hWnd). The system continually monitors each of these
windows for signs of activity or events. Events can occur through user actions such as a mouse click or a key press, through programmatic control, or even as a result of another window's actions.

Each time an event occurs, it causes a message to be sent to the operating system. The system processes the message and broadcasts it to the other windows. Each window can then take the
appropriate action based on its own instructions for dealing with that particular message (for example, repainting itself when it has been uncovered by another window).

As you might imagine, dealing with all of the possible combinations of windows, events and messages could be mind-boggling. Fortunately, Visual Basic insulates you from having to deal with all of
the low-level message handling. Many of the messages are handled automatically by Visual Basic; others are exposed as Event procedures for your convenience. This allows you to quickly create
powerful applications without having to deal with unnecessary details.

Understanding the Event-Driven Model

In traditional or "procedural" applications, the application itself controls which portions of code execute and in what sequence. Execution starts with the first line of code and follows a predefined
path through the application, calling procedures as needed.

In an event-driven application, the code doesn't follow a predetermined path — it executes different code sections in response to events. Events can be triggered by the user's actions, by
messages from the system or other applications, or even from the application itself. The sequence of these events determines the sequence in which the code executes, thus the path through the
application's code differs each time the program runs.

Because you can't predict the sequence of events, your code must make certain assumptions about the "state of the world" when it executes. When you make assumptions (for example, that an
entry field must contain a value before running a procedure to process that value), you should structure your application in such a way as to make sure that the assumption will always be valid
(for example, disabling the command button that starts the procedure until the entry field contains a value).

Your code can also trigger events during execution. For example, programmatically changing the text in a text box cause the text box's Change event to occur. This would cause the code (if any)
contained in the Change event to execute. If you assumed that this event would only be triggered by user interaction, you might see unexpected results. It is for this reason that it is important to
understand the event-driven model and keep it in mind when designing your application.

Interactive Development

The traditional application development process can be broken into three distinct steps: writing, compiling, and testing code. Unlike traditional languages, Visual Basic uses an interactive approach
to development, blurring the distinction between the three steps.

With most languages, if you make a mistake in writing your code, the error is caught by the compiler when you start to compile your application. You must then find and fix the error and begin the
compile cycle again, repeating the process for each error found. Visual Basic interprets your code as you enter it, catching and highlighting most syntax or spelling errors on the fly. It's almost like
having an expert watching over your shoulder as you enter your code.

In addition to catching errors on the fly, Visual Basic also partially compiles the code as it is entered. When you are ready to run and test your application, there is only a brief delay to finish
compiling. If the compiler finds an error, it is highlighted in your code. You can fix the error and continue compiling without having to start over.

Because of the interactive nature of Visual Basic, you'll find yourself running your application frequently as you develop it. This way you can test the effects of your code as you work rather than
waiting to compile later.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconvisualbasicconcepts.asp?frame=true (1 of 2) [11/17/2002 10:32:20 PM]


Visual Basic Concepts

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconvisualbasicconcepts.asp?frame=true (2 of 2) [11/17/2002 10:32:20 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Visual Basic Concepts

See Also

Up One Level In order to understand the application development process, it is helpful to understand some of the key concepts upon which Visual Basic is built. Because Visual Basic is a Windows
development language, some familiarity with the Windows environment is necessary. If you are new to Windows programming, you need to be aware of some fundamental differences between
Visual Basic Concepts programming for Windows versus other environments.

Elements of the Integrated Development Environment


Your First Visual Basic Application How Windows Works: Windows, Events and Messages

A complete discussion of the inner workings of Windows would require an entire book. A deep understanding of all of the technical details isn't necessary. A simplified version of the workings of
Windows involves three key concepts: windows, events and messages.

Think of a window as simply a rectangular region with its own boundaries. You are probably already aware of several different types of windows: an Explorer window in Windows, a document
window within your word processing program, or a dialog box that pops up to remind you of an appointment. While these are the most common examples, there are actually many other types
of windows. A command button is a window. Icons, text boxes, option buttons and menu bars are all windows.

The Microsoft Windows operating system manages all of these many windows by assigning each one a unique id number (window handle or hWnd). The system continually monitors each of
these windows for signs of activity or events. Events can occur through user actions such as a mouse click or a key press, through programmatic control, or even as a result of another
window's actions.

Each time an event occurs, it causes a message to be sent to the operating system. The system processes the message and broadcasts it to the other windows. Each window can then take the
appropriate action based on its own instructions for dealing with that particular message (for example, repainting itself when it has been uncovered by another window).

As you might imagine, dealing with all of the possible combinations of windows, events and messages could be mind-boggling. Fortunately, Visual Basic insulates you from having to deal with
all of the low-level message handling. Many of the messages are handled automatically by Visual Basic; others are exposed as Event procedures for your convenience. This allows you to
quickly create powerful applications without having to deal with unnecessary details.

Understanding the Event-Driven Model

In traditional or "procedural" applications, the application itself controls which portions of code execute and in what sequence. Execution starts with the first line of code and follows a
predefined path through the application, calling procedures as needed.

In an event-driven application, the code doesn't follow a predetermined path — it executes different code sections in response to events. Events can be triggered by the user's actions, by
messages from the system or other applications, or even from the application itself. The sequence of these events determines the sequence in which the code executes, thus the path through
the application's code differs each time the program runs.

Because you can't predict the sequence of events, your code must make certain assumptions about the "state of the world" when it executes. When you make assumptions (for example, that
an entry field must contain a value before running a procedure to process that value), you should structure your application in such a way as to make sure that the assumption will always be
valid (for example, disabling the command button that starts the procedure until the entry field contains a value).

Your code can also trigger events during execution. For example, programmatically changing the text in a text box cause the text box's Change event to occur. This would cause the code (if
any) contained in the Change event to execute. If you assumed that this event would only be triggered by user interaction, you might see unexpected results. It is for this reason that it is
important to understand the event-driven model and keep it in mind when designing your application.

Interactive Development

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconvisualbasicconcepts.asp (1 of 2) [11/17/2002 10:32:23 PM]


Welcome to the MSDN Library
The traditional application development process can be broken into three distinct steps: writing, compiling, and testing code. Unlike traditional languages, Visual Basic uses an interactive
approach to development, blurring the distinction between the three steps.

With most languages, if you make a mistake in writing your code, the error is caught by the compiler when you start to compile your application. You must then find and fix the error and begin
the compile cycle again, repeating the process for each error found. Visual Basic interprets your code as you enter it, catching and highlighting most syntax or spelling errors on the fly. It's
almost like having an expert watching over your shoulder as you enter your code.

In addition to catching errors on the fly, Visual Basic also partially compiles the code as it is entered. When you are ready to run and test your application, there is only a brief delay to finish
compiling. If the compiler finds an error, it is highlighted in your code. You can fix the error and continue compiling without having to start over.

Because of the interactive nature of Visual Basic, you'll find yourself running your application frequently as you develop it. This way you can test the effects of your code as you work rather
than waiting to compile later.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconvisualbasicconcepts.asp (2 of 2) [11/17/2002 10:32:23 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Elements of the Integrated Development Environment

See Also

Up One Level The working environment in Visual Basic is often referred to as the integrated development environment or IDE because it integrates many different functions such as design, editing,
compiling, and debugging within a common environment. In most traditional development tools, each of these functions would operate as a separate program, each with its own interface. In
Starting the Visual Basic IDE this section, the following topics are discussed:

Integrated Development Environment Elements


Environment Options ● Starting the Visual Basic IDE Getting up and running.

● Integrated Development Environment Elements An introduction to the various parts of the IDE.

● Environment Options Configuring Visual Basic to your personal preferences.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconelementsofintegrateddevelopmentenvironment.asp [11/17/2002 10:32:28 PM]


Starting the Visual Basic IDE

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic > Elements of the Integrated Development Environment

Visual Basic Concepts

Starting the Visual Basic IDE

See Also

When you run the Visual Basic Setup program, it allows you to place the program items in an existing program group or create a new program group and new program items for Visual Basic in Windows. You are then ready
to start Visual Basic from Windows.

To start Visual Basic from Windows

1. Click Start on the Task bar.

2. Select Programs, Visual Studio and then Microsoft Visual Basic 6.0.

–or–

Click Start on the Task bar.

Select Programs.

Use the Windows Explorer to find the Visual Basic executable file.

3. Double-click the Visual Basic icon.

You can also create a shortcut to Visual Basic, and double-click the shortcut.

When you first start Visual Basic, you see the interface of the integrated development environment, as shown in Figure 2.1.

Figure 2.1 The Visual Basic integrated development environment

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconstartingvisualbasicide.asp?frame=true (1 of 2) [11/17/2002 10:32:32 PM]


Starting the Visual Basic IDE

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconstartingvisualbasicide.asp?frame=true (2 of 2) [11/17/2002 10:32:32 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic > Elements of the Integrated Development Environment

MSDN Library GO
Advanced Search Visual Basic Concepts

Starting the Visual Basic IDE

See Also

Up One Level When you run the Visual Basic Setup program, it allows you to place the program items in an existing program group or create a new program group and new program items for Visual Basic in Windows. You are then ready
to start Visual Basic from Windows.
Starting the Visual Basic IDE
Integrated Development Environment Elements To start Visual Basic from Windows
Environment Options
1. Click Start on the Task bar.

2. Select Programs, Visual Studio and then Microsoft Visual Basic 6.0.

–or–

Click Start on the Task bar.

Select Programs.

Use the Windows Explorer to find the Visual Basic executable file.

3. Double-click the Visual Basic icon.

You can also create a shortcut to Visual Basic, and double-click the shortcut.

When you first start Visual Basic, you see the interface of the integrated development environment, as shown in Figure 2.1.

Figure 2.1 The Visual Basic integrated development environment

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconstartingvisualbasicide.asp (1 of 2) [11/17/2002 10:32:33 PM]


Welcome to the MSDN Library

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconstartingvisualbasicide.asp (2 of 2) [11/17/2002 10:32:33 PM]


Integrated Development Environment Elements

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic > Elements of the Integrated
Development Environment

Visual Basic Concepts

Integrated Development Environment Elements

See Also

The Visual Basic integrated development environment (IDE) consists of the following elements.

Menu Bar

Displays the commands you use to work with Visual Basic. Besides the standard File, Edit, View, Window, and Help menus, menus are provided to access functions specific to programming such as
Project, Format, or Debug.

Context Menus

Contain shortcuts to frequently performed actions. To open a context menu, click the right mouse button on the object you're using. The specific list of shortcuts available from context menus
depends on the part of the environment where you click the right mouse button. For example, the context menu displayed when you right click on the Toolbox lets you display the Components
dialog box, hide the Toolbox, dock or undock the Toolbox, or add a custom tab to the Toolbox.

Toolbars

Provide quick access to commonly used commands in the programming environment. You click a button on the toolbar once to carry out the action represented by that button. By default, the
Standard toolbar is displayed when you start Visual Basic. Additional toolbars for editing, form design, and debugging can be toggled on or off from the Toolbars command on the View menu.

Toolbars can be docked beneath the menu bar or can "float" if you select the vertical bar on the left edge and drag it away from the menu bar.

Toolbox

Provides a set of tools that you use at design time to place controls on a form. In addition to the default toolbox layout, you can create your own custom layouts by selecting Add Tab from the
context menu and adding controls to the resulting tab.

For More Information To learn more about specific controls, see "Forms, Controls, and Menus" and "Using Visual Basic's Standard Controls." For information on how to add controls to the
Toolbox, see "Adding Controls to a Project" in "Managing Projects."

Project Explorer Window

Lists the forms and modules in your current project. A project is the collection of files you use to build an application.

For More Information For information on projects, see "Managing Projects."

Properties Window

Lists the property settings for the selected form or control. A property is a characteristic of an object, such as size, caption, or color.

For More Information For information on properties, see "Understanding Properties, Methods, and Events" in "Forms, Controls, and Menus."

Object Browser

Lists objects available for use in your project and gives you a quick way to navigate through your code. You can use the Object Browser to explore objects in Visual Basic and other applications,
see what methods and properties are available for those objects, and paste code procedures into your application.

For More Information For more information on using the Object Browser to view procedures, see "Finding Out About Objects" in "Programming with Objects." For details on using add-ins to
extend the Visual Basic programming environment, see "Using Wizards and Add-ins" in "Managing Projects."

Form Designer

Serves as a window that you customize to design the interface of your application. You add controls, graphics, and pictures to a form to create the look you want. Each form in your application has
its own form designer window.

http://msdn.microsoft.com/library/en-us/vbcon98/...teddevelopmentenvironmentelements.asp?frame=true (1 of 2) [11/17/2002 10:32:38 PM]


Integrated Development Environment Elements

For More Information To learn how to add controls to an application, see "Your First Visual Basic Application" later in this chapter. To learn more about designing an interface, see "Creating a
User Interface."

Code Editor Window

Serves as an editor for entering application code. A separate code editor window is created for each form or code module in your application.

For More Information To learn more about entering code and using the code editor, see "Programming Fundamentals."

Form Layout Window

The Form Layout window (Figure 2.2) allows you to position the forms in your application using a small graphical representation of the screen.

Figure 2.2 The Form Layout window

Immediate, Locals, and Watch Windows

These additional windows are provided for use in debugging your application. They are only available when you are running your application within the IDE.

For More Information To learn more about debugging and using the debug windows, see "Debugging Your Code and Handling Errors."

Note You can also add features to the Visual Basic interface by using a program called an add-in. Add-ins, which are available from Microsoft and third-party developers, can provide features like
source code control, which allows you to support group development projects.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/...teddevelopmentenvironmentelements.asp?frame=true (2 of 2) [11/17/2002 10:32:38 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic > Elements of the Integrated
Development Environment
MSDN Library GO
Advanced Search
Visual Basic Concepts

Integrated Development Environment Elements

See Also

Up One Level The Visual Basic integrated development environment (IDE) consists of the following elements.
Starting the Visual Basic IDE
Integrated Development Environment Elements Menu Bar

Environment Options
Displays the commands you use to work with Visual Basic. Besides the standard File, Edit, View, Window, and Help menus, menus are provided to access functions specific to programming
such as Project, Format, or Debug.

Context Menus

Contain shortcuts to frequently performed actions. To open a context menu, click the right mouse button on the object you're using. The specific list of shortcuts available from context menus
depends on the part of the environment where you click the right mouse button. For example, the context menu displayed when you right click on the Toolbox lets you display the Components
dialog box, hide the Toolbox, dock or undock the Toolbox, or add a custom tab to the Toolbox.

Toolbars

Provide quick access to commonly used commands in the programming environment. You click a button on the toolbar once to carry out the action represented by that button. By default, the
Standard toolbar is displayed when you start Visual Basic. Additional toolbars for editing, form design, and debugging can be toggled on or off from the Toolbars command on the View menu.

Toolbars can be docked beneath the menu bar or can "float" if you select the vertical bar on the left edge and drag it away from the menu bar.

Toolbox

Provides a set of tools that you use at design time to place controls on a form. In addition to the default toolbox layout, you can create your own custom layouts by selecting Add Tab from the
context menu and adding controls to the resulting tab.

For More Information To learn more about specific controls, see "Forms, Controls, and Menus" and "Using Visual Basic's Standard Controls." For information on how to add controls to the
Toolbox, see "Adding Controls to a Project" in "Managing Projects."

Project Explorer Window

Lists the forms and modules in your current project. A project is the collection of files you use to build an application.

For More Information For information on projects, see "Managing Projects."

Properties Window

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconintegrateddevelopmentenvironmentelements.asp (1 of 3) [11/17/2002 10:32:40 PM]


Welcome to the MSDN Library
Lists the property settings for the selected form or control. A property is a characteristic of an object, such as size, caption, or color.

For More Information For information on properties, see "Understanding Properties, Methods, and Events" in "Forms, Controls, and Menus."

Object Browser

Lists objects available for use in your project and gives you a quick way to navigate through your code. You can use the Object Browser to explore objects in Visual Basic and other
applications, see what methods and properties are available for those objects, and paste code procedures into your application.

For More Information For more information on using the Object Browser to view procedures, see "Finding Out About Objects" in "Programming with Objects." For details on using add-ins to
extend the Visual Basic programming environment, see "Using Wizards and Add-ins" in "Managing Projects."

Form Designer

Serves as a window that you customize to design the interface of your application. You add controls, graphics, and pictures to a form to create the look you want. Each form in your application
has its own form designer window.

For More Information To learn how to add controls to an application, see "Your First Visual Basic Application" later in this chapter. To learn more about designing an interface, see "Creating
a User Interface."

Code Editor Window

Serves as an editor for entering application code. A separate code editor window is created for each form or code module in your application.

For More Information To learn more about entering code and using the code editor, see "Programming Fundamentals."

Form Layout Window

The Form Layout window (Figure 2.2) allows you to position the forms in your application using a small graphical representation of the screen.

Figure 2.2 The Form Layout window

Immediate, Locals, and Watch Windows

These additional windows are provided for use in debugging your application. They are only available when you are running your application within the IDE.

For More Information To learn more about debugging and using the debug windows, see "Debugging Your Code and Handling Errors."

Note You can also add features to the Visual Basic interface by using a program called an add-in. Add-ins, which are available from Microsoft and third-party developers, can provide features
like source code control, which allows you to support group development projects.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconintegrateddevelopmentenvironmentelements.asp (2 of 3) [11/17/2002 10:32:40 PM]


Welcome to the MSDN Library
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconintegrateddevelopmentenvironmentelements.asp (3 of 3) [11/17/2002 10:32:40 PM]


Environment Options

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic > Elements of the Integrated
Development Environment

Visual Basic Concepts

Environment Options

See Also

Visual Basic provides a great deal of flexibility, allowing you to configure the working environment to best suit your individual style. You can choose between a single or multiple document
interface, and you can adjust the size and positioning of the various Integrated Development Environment (IDE) elements. Your layout will persist between sessions of Visual Basic.

SDI or MDI Interface

Two different styles are available for the Visual Basic IDE: single document interface (SDI) or multiple document interface (MDI). With the SDI option, all of the IDE windows are free to be moved
anywhere on screen; as long as Visual Basic is the current application, they will remain on top of any other applications. With the MDI option, all of the IDE windows are contained within a single
resizable parent window.

To switch between SDI and MDI modes

1. Select Options from the Tools menu.

The Options dialog box is displayed.

2. Select the Advanced tab.

3. Check or uncheck the SDI Development Environment check box.

The IDE will start in the selected mode the next time you start Visual Basic.

–or–

Run Visual Basic from the command line with a /sdi or /mdi parameter.

Docking Windows

Many of the windows in the IDE can be docked, or connected, to each other or to the edge of the screen. These include the Toolbox, Form Layout Window, Project Explorer, Properties window,
Color Palette, and Immediate, Locals, and Watch windows.

With the MDI option, windows can be docked to any side of the parent window; with SDI they can only be docked beneath the menu bar. Docking capabilities can be toggled on or off for a given
window by selecting the appropriate check box on the Docking tab of the Options dialog box, available from the Options command on the Tools menu.

To dock or undock a window

1. Select the window you wish to dock or undock.

2. Drag the window to the desired location by holding down the left mouse button.

3. The outline of the window will be displayed as you drag.

4. Release the mouse button.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconenvironmentoptions.asp?frame=true [11/17/2002 10:32:45 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic > Elements of the Integrated
Development Environment
MSDN Library GO
Advanced Search
Visual Basic Concepts

Environment Options

See Also

Up One Level Visual Basic provides a great deal of flexibility, allowing you to configure the working environment to best suit your individual style. You can choose between a single or multiple document
Starting the Visual Basic IDE interface, and you can adjust the size and positioning of the various Integrated Development Environment (IDE) elements. Your layout will persist between sessions of Visual Basic.

Integrated Development Environment Elements


SDI or MDI Interface
Environment Options
Two different styles are available for the Visual Basic IDE: single document interface (SDI) or multiple document interface (MDI). With the SDI option, all of the IDE windows are free to be
moved anywhere on screen; as long as Visual Basic is the current application, they will remain on top of any other applications. With the MDI option, all of the IDE windows are contained
within a single resizable parent window.

To switch between SDI and MDI modes

1. Select Options from the Tools menu.

The Options dialog box is displayed.

2. Select the Advanced tab.

3. Check or uncheck the SDI Development Environment check box.

The IDE will start in the selected mode the next time you start Visual Basic.

–or–

Run Visual Basic from the command line with a /sdi or /mdi parameter.

Docking Windows

Many of the windows in the IDE can be docked, or connected, to each other or to the edge of the screen. These include the Toolbox, Form Layout Window, Project Explorer, Properties window,
Color Palette, and Immediate, Locals, and Watch windows.

With the MDI option, windows can be docked to any side of the parent window; with SDI they can only be docked beneath the menu bar. Docking capabilities can be toggled on or off for a
given window by selecting the appropriate check box on the Docking tab of the Options dialog box, available from the Options command on the Tools menu.

To dock or undock a window

1. Select the window you wish to dock or undock.

2. Drag the window to the desired location by holding down the left mouse button.

3. The outline of the window will be displayed as you drag.

4. Release the mouse button.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconenvironmentoptions.asp (1 of 2) [11/17/2002 10:32:46 PM]


Welcome to the MSDN Library

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconenvironmentoptions.asp (2 of 2) [11/17/2002 10:32:46 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Your First Visual Basic Application

See Also

Up One Level Creating an application in Visual Basic is simple. How simple? For the answer, try out the Hello, Visual Basic and Firstapp applications that follow.

Hello, Visual Basic


The Firstapp Sample Application ● Hello, Visual Basic Step-by-step creation of the classic "Hello World" application.

● The Firstapp Sample Application Create your first "real" application by duplicating the Firstapp sample application.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconyourfirstvisualbasicapplication.asp [11/17/2002 10:33:07 PM]


Hello, Visual Basic

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic > Your First Visual Basic Application

Visual Basic Concepts

Hello, Visual Basic

See Also

There are three main steps to creating an application in Visual Basic:

1. Create the interface.

2. Set properties.

3. Write code.

To see how this is done, use the steps in the following procedures to create a simple application that consists of a text box and a command button. When you click the command button, the message "Hello, world!"
appears in the text box.

Creating the Interface

Forms are the foundation for creating the interface of an application. You can use forms to add windows and dialog boxes to your application. You can also use them as containers for items that are not a visible part of
the application's interface. For example, you might have a form in your application that serves as a container for graphics that you plan to display in other forms.

The first step in building a Visual Basic application is to create the forms that will be the basis for your application's interface. Then you draw the objects that make up the interface on the forms you create. For this
first application, you'll use two controls from the Toolbox.

Button Control

Text box

Command button

To draw a control using the Toolbox

1. Click the tool for the control you choose to draw — in this case, the text box.

2. Move the pointer onto your form. The pointer becomes a cross hair, as shown in Figure 2.3.

Figure 2.3 Drawing a text box with the Toolbox

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconhellovisualbasic.asp?frame=true (1 of 6) [11/17/2002 10:33:11 PM]


Hello, Visual Basic

3. Place the cross hair where you want the upper-left corner of the control.

4. Drag the cross hair until the control is the size you want. (Dragging means holding the left mouse button down while you move an object with the mouse.)

5. Release the mouse button.

The control appears on the form.

Another simple way to add a control to a form is to double-click the button for that control in the Toolbox. This creates a default-size control located in the center of the form; then you can move the control to another
location on the form.

Resizing, Moving, and Locking Controls


Notice that small rectangular boxes called sizing handles appear at the corners of the control; you'll use these sizing handles in the next step as you resize the control. You can also use the mouse, keyboard, and
menu commands to move controls, lock and unlock control positions, and adjust their positions.

To resize a control

1. Select the control you intend to resize by clicking it with the mouse.

Sizing handles appear on the control.

2. Position the mouse pointer on a sizing handle, and drag it until the control is the size you choose.

The corner handles resize controls horizontally and vertically, while the side handles resize in only one direction.

3. Release the mouse button.

–or–

Use SHIFT with the arrow keys to resize the selected control.

To move a control

● Use the mouse to drag the control to a new location on the form.

–or–

Use the Properties window to change the Top and Left properties.

When a control is selected, you can use CTRL with the arrow keys to move the control one grid unit at a time. If the grid is turned off, the control moves one pixel at a time.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconhellovisualbasic.asp?frame=true (2 of 6) [11/17/2002 10:33:11 PM]


Hello, Visual Basic

To lock all control positions

● From the Format menu, choose Lock Controls.

–or–

Click the Lock Controls Toggle button on the Form Editor toolbar.

This will lock all controls on the form in their current positions so that you don't inadvertently move them once you have them in the desired location. This will lock controls only on the selected form; controls on other
forms are untouched. This is a toggle command, so you can also use it to unlock control positions.

To adjust the position of locked controls

● You can "nudge" the control that has the focus by holding CTRL down and pressing the appropriate arrow key.

–or–

You can change the control's Top and Left properties in the Property window.

You now have the interface for the "Hello, world!" application, as shown in Figure 2.4.

Figure 2.4 The interface for the "Hello, world!" application

Setting Properties

The next step is to set properties for the objects you've created. The Properties window (Figure 2.5) provides an easy way to set properties for all objects on a form. To open the Properties window, choose the
Properties Window command from the View menu, click the Properties Window button on the toolbar, or use the context menu for the control.

Figure 2.5 The Properties window

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconhellovisualbasic.asp?frame=true (3 of 6) [11/17/2002 10:33:11 PM]


Hello, Visual Basic

The Properties window consists of the following elements:

● Object box — Displays the name of the object for which you can set properties. Click the arrow to the right of the object box to display the list of objects for the current form.

● Sort tabs — Choose between an alphabetic listing of properties or a hierarchical view divided by logical categories, such as those dealing with appearance, fonts, or position.

● Properties list — The left column displays all of the properties for the selected object. You can edit and view settings in the right column.

To set properties from the Properties window

1. From the View menu, choose Properties, or click the Properties button on the toolbar.

The Properties window displays the settings for the selected form or control.

2. From the Properties list, select the name of a property.

3. In the right column, type or select the new property setting.

Enumerated properties have a predefined list of settings. You can display the list by clicking the down arrow at the right of the Settings box, or you can cycle through the list by double-clicking a list item.

For the "Hello, world!" example, you'll need to change three property settings. Use the default settings for all other properties.

Object Property Setting

Form Caption Hello, world!

Text box Text (Empty)

Command button Caption OK

Setting the Icon Property


All forms in Visual Basic have a generic, default icon that appears when you minimize that form. However, you will probably change this icon to one that illustrates the use of the form or your application. To assign an
icon to a form, set the Icon property for that form. You can use 32 x 32 pixel icons that were standard in 16-bit versions of Microsoft Windows and are also used in Windows 95/98 and Windows NT, as well as the 16 x
16 pixel icons used in Windows 95/98.

Writing Code

The Code Editor window is where you write Visual Basic code for your application. Code consists of language statements, constants, and declarations. Using the Code Editor window, you can quickly view and edit any
of the code in your application.

To open the Code window

● Double-click the form or control for which you choose to write code.

–or–

From the Project Explorer window, select the name of a form or module, and choose the View Code button.

Figure 2.6 shows the Code Editor window that appears when you double-click the Command button control, and the events for that command.

Figure 2.6 The Code Editor window

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconhellovisualbasic.asp?frame=true (4 of 6) [11/17/2002 10:33:11 PM]


Hello, Visual Basic

You can choose to display all procedures in the same Code window, or display a single procedure at a time.

To display all procedures in the same Code window

1. From the Tools menu, select the Options dialog box.

2. On the Editor tab in the Options dialog box, select the check box to the left of Default to Full Module View. The check box to the left of Procedure Separator adds or removes a separator line between procedures.

–or–

Click the Full Module View button in the lower left corner of the Code Editor window.

To display one procedure at a time in the Code window

1. From the Tools menu, select the Options dialog box.

2. On the Editor tab in the Options dialog box, clear the check box to the left of Default to Full Module View.

–or–

Click the Procedure View button in the lower left corner of the Code Editor window.

The Code window includes the following elements:

● Object list box — Displays the name of the selected object. Click the arrow to the right of the list box to display a list of all objects associated with the form.

● Procedure list box — Lists the procedures, or events, for an object. The box displays the name of the selected procedure — in this case, Click. Choose the arrow to the right of the box to display all the procedures for the object.

Creating Event Procedures


Code in a Visual Basic application is divided into smaller blocks called procedures. An event procedure, such as those you'll create here, contains code that is executed when an event occurs (such as when a user
clicks a button). An event procedure for a control combines the control's actual name (specified in the Name property), an underscore (_), and the event name. For example, if you want a command button named
Command1 to invoke an event procedure when it is clicked, use the procedure Command1_Click.

To create an event procedure

1. In the Object list box, select the name of an object in the active form. (The active form is the form that currently has the focus.)

For this example, choose the command button, Command1.

2. In the Procedure list box, select the name of an event for the selected object.

Here, the Click procedure is already selected, because it's the default procedure for a command button. Note that a template for the event procedure is now displayed in the Code window.

3. Type the following code between the Sub and End Sub statements:

Text1.Text = "Hello, world!"

The event procedure should look like this:

Private Sub Command1_Click ()


Text1.Text = "Hello, world!"
End Sub

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconhellovisualbasic.asp?frame=true (5 of 6) [11/17/2002 10:33:11 PM]


Hello, Visual Basic

You'll note here that the code is simply changing the Text property of the control named Text1 to read "Hello, world!" The syntax for this example takes the form of object.property, where Text1 is the object and Text
is the property. You can use this syntax to change property settings for any form or control in response to events that occur while your application is running.

For More Information For information on creating other types of procedures, see "Introduction to Procedures" in "Programming Fundamentals."

Running the Application

To run the application, choose Start from the Run menu, or click the Start button on the toolbar, or press F5. Click the command button you've created on the form, and you'll see "Hello, world!" displayed in the text
box.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconhellovisualbasic.asp?frame=true (6 of 6) [11/17/2002 10:33:11 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic > Your First Visual Basic Application

MSDN Library GO
Advanced Search Visual Basic Concepts

Hello, Visual Basic

See Also

Up One Level There are three main steps to creating an application in Visual Basic:

Hello, Visual Basic


The Firstapp Sample Application 1. Create the interface.

2. Set properties.

3. Write code.

To see how this is done, use the steps in the following procedures to create a simple application that consists of a text box and a command button. When you click the command button, the message "Hello, world!"
appears in the text box.

Creating the Interface

Forms are the foundation for creating the interface of an application. You can use forms to add windows and dialog boxes to your application. You can also use them as containers for items that are not a visible part of
the application's interface. For example, you might have a form in your application that serves as a container for graphics that you plan to display in other forms.

The first step in building a Visual Basic application is to create the forms that will be the basis for your application's interface. Then you draw the objects that make up the interface on the forms you create. For this
first application, you'll use two controls from the Toolbox.

Button Control

Text box

Command button

To draw a control using the Toolbox

1. Click the tool for the control you choose to draw — in this case, the text box.

2. Move the pointer onto your form. The pointer becomes a cross hair, as shown in Figure 2.3.

Figure 2.3 Drawing a text box with the Toolbox

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconhellovisualbasic.asp (1 of 6) [11/17/2002 10:33:13 PM]


Welcome to the MSDN Library

3. Place the cross hair where you want the upper-left corner of the control.

4. Drag the cross hair until the control is the size you want. (Dragging means holding the left mouse button down while you move an object with the mouse.)

5. Release the mouse button.

The control appears on the form.

Another simple way to add a control to a form is to double-click the button for that control in the Toolbox. This creates a default-size control located in the center of the form; then you can move the control to another
location on the form.

Resizing, Moving, and Locking Controls


Notice that small rectangular boxes called sizing handles appear at the corners of the control; you'll use these sizing handles in the next step as you resize the control. You can also use the mouse, keyboard, and
menu commands to move controls, lock and unlock control positions, and adjust their positions.

To resize a control

1. Select the control you intend to resize by clicking it with the mouse.

Sizing handles appear on the control.

2. Position the mouse pointer on a sizing handle, and drag it until the control is the size you choose.

The corner handles resize controls horizontally and vertically, while the side handles resize in only one direction.

3. Release the mouse button.

–or–

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconhellovisualbasic.asp (2 of 6) [11/17/2002 10:33:13 PM]


Welcome to the MSDN Library
Use SHIFT with the arrow keys to resize the selected control.

To move a control

● Use the mouse to drag the control to a new location on the form.

–or–

Use the Properties window to change the Top and Left properties.

When a control is selected, you can use CTRL with the arrow keys to move the control one grid unit at a time. If the grid is turned off, the control moves one pixel at a time.

To lock all control positions

● From the Format menu, choose Lock Controls.

–or–

Click the Lock Controls Toggle button on the Form Editor toolbar.

This will lock all controls on the form in their current positions so that you don't inadvertently move them once you have them in the desired location. This will lock controls only on the selected form; controls on other
forms are untouched. This is a toggle command, so you can also use it to unlock control positions.

To adjust the position of locked controls

● You can "nudge" the control that has the focus by holding CTRL down and pressing the appropriate arrow key.

–or–

You can change the control's Top and Left properties in the Property window.

You now have the interface for the "Hello, world!" application, as shown in Figure 2.4.

Figure 2.4 The interface for the "Hello, world!" application

Setting Properties

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconhellovisualbasic.asp (3 of 6) [11/17/2002 10:33:13 PM]


Welcome to the MSDN Library

The next step is to set properties for the objects you've created. The Properties window (Figure 2.5) provides an easy way to set properties for all objects on a form. To open the Properties window, choose the
Properties Window command from the View menu, click the Properties Window button on the toolbar, or use the context menu for the control.

Figure 2.5 The Properties window

The Properties window consists of the following elements:

● Object box — Displays the name of the object for which you can set properties. Click the arrow to the right of the object box to display the list of objects for the current form.

● Sort tabs — Choose between an alphabetic listing of properties or a hierarchical view divided by logical categories, such as those dealing with appearance, fonts, or position.

● Properties list — The left column displays all of the properties for the selected object. You can edit and view settings in the right column.

To set properties from the Properties window

1. From the View menu, choose Properties, or click the Properties button on the toolbar.

The Properties window displays the settings for the selected form or control.

2. From the Properties list, select the name of a property.

3. In the right column, type or select the new property setting.

Enumerated properties have a predefined list of settings. You can display the list by clicking the down arrow at the right of the Settings box, or you can cycle through the list by double-clicking a list item.

For the "Hello, world!" example, you'll need to change three property settings. Use the default settings for all other properties.

Object Property Setting

Form Caption Hello, world!

Text box Text (Empty)

Command button Caption OK

Setting the Icon Property


All forms in Visual Basic have a generic, default icon that appears when you minimize that form. However, you will probably change this icon to one that illustrates the use of the form or your application. To assign an
icon to a form, set the Icon property for that form. You can use 32 x 32 pixel icons that were standard in 16-bit versions of Microsoft Windows and are also used in Windows 95/98 and Windows NT, as well as the 16 x
16 pixel icons used in Windows 95/98.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconhellovisualbasic.asp (4 of 6) [11/17/2002 10:33:13 PM]


Welcome to the MSDN Library
Writing Code

The Code Editor window is where you write Visual Basic code for your application. Code consists of language statements, constants, and declarations. Using the Code Editor window, you can quickly view and edit any
of the code in your application.

To open the Code window

● Double-click the form or control for which you choose to write code.

–or–

From the Project Explorer window, select the name of a form or module, and choose the View Code button.

Figure 2.6 shows the Code Editor window that appears when you double-click the Command button control, and the events for that command.

Figure 2.6 The Code Editor window

You can choose to display all procedures in the same Code window, or display a single procedure at a time.

To display all procedures in the same Code window

1. From the Tools menu, select the Options dialog box.

2. On the Editor tab in the Options dialog box, select the check box to the left of Default to Full Module View. The check box to the left of Procedure Separator adds or removes a separator line between procedures.

–or–

Click the Full Module View button in the lower left corner of the Code Editor window.

To display one procedure at a time in the Code window

1. From the Tools menu, select the Options dialog box.

2. On the Editor tab in the Options dialog box, clear the check box to the left of Default to Full Module View.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconhellovisualbasic.asp (5 of 6) [11/17/2002 10:33:13 PM]


Welcome to the MSDN Library
–or–

Click the Procedure View button in the lower left corner of the Code Editor window.

The Code window includes the following elements:

● Object list box — Displays the name of the selected object. Click the arrow to the right of the list box to display a list of all objects associated with the form.

● Procedure list box — Lists the procedures, or events, for an object. The box displays the name of the selected procedure — in this case, Click. Choose the arrow to the right of the box to display all the procedures for the object.

Creating Event Procedures


Code in a Visual Basic application is divided into smaller blocks called procedures. An event procedure, such as those you'll create here, contains code that is executed when an event occurs (such as when a user
clicks a button). An event procedure for a control combines the control's actual name (specified in the Name property), an underscore (_), and the event name. For example, if you want a command button named
Command1 to invoke an event procedure when it is clicked, use the procedure Command1_Click.

To create an event procedure

1. In the Object list box, select the name of an object in the active form. (The active form is the form that currently has the focus.)

For this example, choose the command button, Command1.

2. In the Procedure list box, select the name of an event for the selected object.

Here, the Click procedure is already selected, because it's the default procedure for a command button. Note that a template for the event procedure is now displayed in the Code window.

3. Type the following code between the Sub and End Sub statements:

Text1.Text = "Hello, world!"

The event procedure should look like this:

Private Sub Command1_Click ()


Text1.Text = "Hello, world!"
End Sub

You'll note here that the code is simply changing the Text property of the control named Text1 to read "Hello, world!" The syntax for this example takes the form of object.property, where Text1 is the object and Text
is the property. You can use this syntax to change property settings for any form or control in response to events that occur while your application is running.

For More Information For information on creating other types of procedures, see "Introduction to Procedures" in "Programming Fundamentals."

Running the Application

To run the application, choose Start from the Run menu, or click the Start button on the toolbar, or press F5. Click the command button you've created on the form, and you'll see "Hello, world!" displayed in the text
box.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconhellovisualbasic.asp (6 of 6) [11/17/2002 10:33:13 PM]


The Firstapp Sample Application

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic > Your First Visual Basic Application

Visual Basic Concepts

The Firstapp Sample Application

See Also

Visual Basic provides you with a wealth of tools beyond the ones used in this first application, so you'll soon use many other features to manage and customize your applications. Reviewing sample
applications can be an excellent way to learn more about Visual Basic. The following example illustrates how easy it can be to create a useful application in Visual Basic.

The Firstapp application demonstrates how a data control and a grid control can be used to display a table of information from a database. Visual Basic makes it easy to access database
information from within your application. The data control provides the ability to navigate through the database recordset, synchronizing the display of records in the grid control with the position
in the recordset.

The application consists of a data control, a MSFlexGrid control, a list box control, and two command buttons. The grid displays a table of information about products retrieved from the Northwind
database. As the user selects an item by using the navigation buttons on the data control, the name of the selected product is displayed in the data control. The user can also add items to a
"shopping list" in the list box control by double-clicking the current selection in the grid.

To add items to the list box, you use the AddItem method. (A method is a Visual Basic function that acts on a particular object, in this case a ListBox object.) The syntax for specifying a method
(object.method) is similar to the syntax for setting a property (object.property). The AddItem method allows you to dynamically add items to the list box while the application is running.
Conversely, the Clear method is used to remove all items from the list box.

For More Information To learn more about methods, see "Understanding Properties, Methods, and Events" in "Forms, Controls, and Menus."

Creating a Project

You begin creating this application by choosing New Project from the File menu, then selecting Standard EXE in the New Project dialog box (when you first start Visual Basic, the New Project dialog
box is presented). Visual Basic creates a new project and displays a new form. To draw the interface, you use a data control, a MSFlexGrid control, a list box control, and two command buttons.
The MSFlexGrid control isn't in the default toolbox, so you'll need to add it:

To add a control to the toolbox

1. Select Components from the context menu for the toolbox. (You can right-click within the toolbox window to display the context menu.)

The Components dialog box will be displayed.

2. Find the MSFlexGrid (Microsoft Flex Grid 6.0) in the Controls list box and select the check box to its left.

3. Click the OK button.

The icon for the MSFlexGrid control will appear in the toolbox.

Use the Toolbox to draw a data control, an MSFlexGrid control, a list box control, and two command buttons on the form. If you don't remember how, check out "Creating the Interface" earlier in
this chapter.

Setting Properties

In the Properties window, set properties for the objects according to the following table. Use the default settings for all other properties.

Object Property Setting

Form Caption Products

Data1 DatabaseName path \Nwind.mdb


RecordSource Products

MSFlexGrid1 DataSource Data1

Command1 Caption Clear

Command2 Caption Exit

The DatabaseName property of the data control must include the actual path to the database. By default, the Nwind.mdb database is installed in the same directory as Visual Basic. When you
select the DatabaseName property in the Properties window, you can click the button to the right of the property to display a standard File Open dialog box to browse for the file. Once the
DatabaseName property has been set, the RecordSource property in the Properties window will contain a list of tables or recordsets for the selected database. Setting the DataSource property of
the MSFlexGrid control to Data1 automatically links the grid to the data control.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconthefirstappsampleapplication.asp?frame=true (1 of 2) [11/17/2002 10:33:18 PM]


The Firstapp Sample Application

Writing Event Code

All the code for the application is contained in the Command1_Click, Command2_Click, Data1_Reposition, and MSFlexGrid1_DblClick event procedures. Double-click the form or control to display
the Code window, and then type the code for each event procedure.

Add this code to the Command1_Click event procedure to clear the list box when the user clicks the button:

Private Sub Command1_Click ()


List1.Clear ' Clears the list box.
End Sub

In the above statement, you are invoking the Clear method of the list box, List1. The Clear method deletes the contents of the list box.

Add this code to the Command2_Click event procedure to unload the form from memory and end the application:

Private Sub Command2_Click ()


Unload Form1
End ' Ends application.
End Sub

In the above procedure, the first statement invokes the Unload event for the form. If you needed to perform a function at shutdown, such as saving a file, you could place that code in the form's
Unload event procedure. The second statement calls the End function, which ends the application.

Add this code to the Data1_Reposition event procedure to update the caption each time a record is selected:

Private Sub Data1_Reposition ()


Data1.Caption = Data1.Recordset("ProductName")
End Sub

In the above statement, you are assigning the value on the right (the contents of the Title field in the Recordset of the data control) to the property on the left (the Caption property of the data
control object).

Add this code to the MSFlexGrid_DblClick event procedure to add an item to the list box when the user double-clicks a selected row:

Private Sub MSFlexGrid1_DblClick ()


List1.AddItem MSFlexGrid1.Text
End Sub

In the above statement, you are invoking the AddItem method of the list box (List1). The text to be added to the list box is contained in the argument of the method, in this case, the value of the
title field in the recordset of the data control. Passing a value to an argument is similar to assigning a value to a property; unlike the assignment statement, the equal sign isn't required.

Saving a Project

You finish your work on the application by choosing Save Project from the File menu. Visual Basic will prompt you separately to save the form and then the project. One possible name for the
project is "Northwind Shopping List." Windows 95, Windows 98, and Windows NT allow you to use file names up to 255 characters in length, and file names can include spaces. Older versions of
Microsoft Windows limited you to file names of eight characters, with a three-character extension.

Enhancing Your Application

You have just completed your first Visual Basic application: one that performs a simple but useful function. You can use this application as a basis for adding similar functionality in your own
applications, substituting your own data instead of Nwind.mdb. Of course, to make this application truly useful, you might want to add functionality to save or print the contents of the list box, to
add additional information such as price and availability, and even to gather credit card information and transmit an order across the Internet. As you continue on through the rest of the
Programmer's Guide, you will find examples of doing all that and a lot more.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconthefirstappsampleapplication.asp?frame=true (2 of 2) [11/17/2002 10:33:18 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic > Your First Visual Basic
Application
MSDN Library GO
Advanced Search
Visual Basic Concepts

The Firstapp Sample Application

See Also

Up One Level Visual Basic provides you with a wealth of tools beyond the ones used in this first application, so you'll soon use many other features to manage and customize your applications. Reviewing
Hello, Visual Basic sample applications can be an excellent way to learn more about Visual Basic. The following example illustrates how easy it can be to create a useful application in Visual Basic.

The Firstapp Sample Application


The Firstapp application demonstrates how a data control and a grid control can be used to display a table of information from a database. Visual Basic makes it easy to access database
information from within your application. The data control provides the ability to navigate through the database recordset, synchronizing the display of records in the grid control with the
position in the recordset.

The application consists of a data control, a MSFlexGrid control, a list box control, and two command buttons. The grid displays a table of information about products retrieved from the
Northwind database. As the user selects an item by using the navigation buttons on the data control, the name of the selected product is displayed in the data control. The user can also add
items to a "shopping list" in the list box control by double-clicking the current selection in the grid.

To add items to the list box, you use the AddItem method. (A method is a Visual Basic function that acts on a particular object, in this case a ListBox object.) The syntax for specifying a method
(object.method) is similar to the syntax for setting a property (object.property). The AddItem method allows you to dynamically add items to the list box while the application is running.
Conversely, the Clear method is used to remove all items from the list box.

For More Information To learn more about methods, see "Understanding Properties, Methods, and Events" in "Forms, Controls, and Menus."

Creating a Project

You begin creating this application by choosing New Project from the File menu, then selecting Standard EXE in the New Project dialog box (when you first start Visual Basic, the New Project
dialog box is presented). Visual Basic creates a new project and displays a new form. To draw the interface, you use a data control, a MSFlexGrid control, a list box control, and two command
buttons. The MSFlexGrid control isn't in the default toolbox, so you'll need to add it:

To add a control to the toolbox

1. Select Components from the context menu for the toolbox. (You can right-click within the toolbox window to display the context menu.)

The Components dialog box will be displayed.

2. Find the MSFlexGrid (Microsoft Flex Grid 6.0) in the Controls list box and select the check box to its left.

3. Click the OK button.

The icon for the MSFlexGrid control will appear in the toolbox.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthefirstappsampleapplication.asp (1 of 3) [11/17/2002 10:33:20 PM]


Welcome to the MSDN Library
Use the Toolbox to draw a data control, an MSFlexGrid control, a list box control, and two command buttons on the form. If you don't remember how, check out "Creating the Interface" earlier
in this chapter.

Setting Properties

In the Properties window, set properties for the objects according to the following table. Use the default settings for all other properties.

Object Property Setting

Form Caption Products

Data1 DatabaseName path \Nwind.mdb


RecordSource Products

MSFlexGrid1 DataSource Data1

Command1 Caption Clear

Command2 Caption Exit

The DatabaseName property of the data control must include the actual path to the database. By default, the Nwind.mdb database is installed in the same directory as Visual Basic. When you
select the DatabaseName property in the Properties window, you can click the button to the right of the property to display a standard File Open dialog box to browse for the file. Once the
DatabaseName property has been set, the RecordSource property in the Properties window will contain a list of tables or recordsets for the selected database. Setting the DataSource property
of the MSFlexGrid control to Data1 automatically links the grid to the data control.

Writing Event Code

All the code for the application is contained in the Command1_Click, Command2_Click, Data1_Reposition, and MSFlexGrid1_DblClick event procedures. Double-click the form or control to
display the Code window, and then type the code for each event procedure.

Add this code to the Command1_Click event procedure to clear the list box when the user clicks the button:

Private Sub Command1_Click ()


List1.Clear ' Clears the list box.
End Sub

In the above statement, you are invoking the Clear method of the list box, List1. The Clear method deletes the contents of the list box.

Add this code to the Command2_Click event procedure to unload the form from memory and end the application:

Private Sub Command2_Click ()


Unload Form1
End ' Ends application.
End Sub

In the above procedure, the first statement invokes the Unload event for the form. If you needed to perform a function at shutdown, such as saving a file, you could place that code in the
form's Unload event procedure. The second statement calls the End function, which ends the application.

Add this code to the Data1_Reposition event procedure to update the caption each time a record is selected:

Private Sub Data1_Reposition ()


Data1.Caption = Data1.Recordset("ProductName")
End Sub

In the above statement, you are assigning the value on the right (the contents of the Title field in the Recordset of the data control) to the property on the left (the Caption property of the data
control object).

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthefirstappsampleapplication.asp (2 of 3) [11/17/2002 10:33:20 PM]


Welcome to the MSDN Library
Add this code to the MSFlexGrid_DblClick event procedure to add an item to the list box when the user double-clicks a selected row:

Private Sub MSFlexGrid1_DblClick ()


List1.AddItem MSFlexGrid1.Text
End Sub

In the above statement, you are invoking the AddItem method of the list box (List1). The text to be added to the list box is contained in the argument of the method, in this case, the value of
the title field in the recordset of the data control. Passing a value to an argument is similar to assigning a value to a property; unlike the assignment statement, the equal sign isn't required.

Saving a Project

You finish your work on the application by choosing Save Project from the File menu. Visual Basic will prompt you separately to save the form and then the project. One possible name for the
project is "Northwind Shopping List." Windows 95, Windows 98, and Windows NT allow you to use file names up to 255 characters in length, and file names can include spaces. Older versions of
Microsoft Windows limited you to file names of eight characters, with a three-character extension.

Enhancing Your Application

You have just completed your first Visual Basic application: one that performs a simple but useful function. You can use this application as a basis for adding similar functionality in your own
applications, substituting your own data instead of Nwind.mdb. Of course, to make this application truly useful, you might want to add functionality to save or print the contents of the list box,
to add additional information such as price and availability, and even to gather credit card information and transmit an order across the Internet. As you continue on through the rest of the
Programmer's Guide, you will find examples of doing all that and a lot more.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthefirstappsampleapplication.asp (3 of 3) [11/17/2002 10:33:20 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics

MSDN Library GO
Advanced Search Visual Basic Concepts

Forms, Controls, and Menus

See Also

Up One Level The first step to creating an application with Visual Basic is to create the interface, the visual part of the application with which the user will interact. Forms and controls are the basic building
blocks used to create the interface; they are the objects that you will work with to build your application.
Understanding Properties, Methods and Events
Designing a Form Forms are objects that expose properties which define their appearance, methods which define their behavior, and events which define their interaction with the user. By setting the properties
Clicking Buttons to Perform Actions of the form and writing Visual Basic code to respond to its events, you customize the object to meet the requirements of your application.

Controls for Displaying and Entering Text


Controls That Present Choices to Users Controls are objects that are contained within form objects. Each type of control has its own set of properties, methods and events that make it suitable for a particular purpose. Some of the
controls you can use in your applications are best suited for entering or displaying text. Other controls let you access other applications and process data as if the remote application was part
Controls That Display Pictures and Graphics of your code.

Additional Controls
Understanding Focus This chapter introduces the basic concepts of working with forms and controls and their associated properties, methods, and events. Many of the standard controls are discussed, as well as
form-specific items such as menus and dialog boxes.
Setting the Tab Order
Menu Basics Topics
Prompting the User with Dialog Boxes
Understanding Properties, Methods and Events

An introduction to objects and their associated properties, methods, and events.

Designing a Form

The basics of working with a form's properties, methods, and events.

Clicking Buttons to Perform Actions

An introduction to the command button control.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconformscontrolsmenus.asp (1 of 3) [11/17/2002 10:33:39 PM]


Welcome to the MSDN Library

Controls for Displaying and Entering Text

An introduction to the label and text box controls.

Controls That Present Choices to Users

An introduction to the check box, option button, list box, combo box, and scroll bar controls.

Controls That Display Pictures and Graphics

An introduction to the picture box, image, shape, and line controls.

Additional Controls

An introduction to the other standard Visual Basic controls.

Understanding Focus

A brief discussion of focus as it applies to controls.

Setting the Tab Order

An introduction to the concepts of tab order within a form.

Menu Basics

An introduction to menu controls and the menu editor.

Prompting the User with Dialog Boxes

An introduction to dialog boxes.

Sample application

Controls.vbp

The code examples in this chapter are taken from the Controls.vbp sample application which is listed in the Samples directory.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconformscontrolsmenus.asp (2 of 3) [11/17/2002 10:33:39 PM]


Welcome to the MSDN Library
Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconformscontrolsmenus.asp (3 of 3) [11/17/2002 10:33:39 PM]


Understanding Properties, Methods and Events

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

Visual Basic Concepts

Understanding Properties, Methods and Events

See Also

Visual Basic forms and controls are objects which expose their own properties, methods and events. Properties can be thought of as an object's attributes, methods as its actions, and events as its
responses.

An everyday object like a child's helium balloon also has properties, methods and events. A balloon's properties include visible attributes such as its height, diameter and color. Other properties
describe its state (inflated or not inflated), or attributes that aren't visible such as its age. By definition, all balloons have these properties; the settings of these properties may differ from one
balloon to another.

A balloon also has inherent methods or actions that it might perform. It has an inflate method (the action of filling it with helium), a deflate method (expelling its contents) and a rise method (if
you were to let go of it). Again, all balloons are capable of these methods.

Balloons also have predefined responses to certain external events. For instance, a balloon would respond to the event of being punctured by deflating itself, or to the event of being released by
rising into the air.

Figure 3.1 Objects have properties, respond to events, and perform methods

If you were able to program a balloon, the Visual Basic code might look like the following. To set the balloon's properties:

Balloon.Color = Red
Balloon.Diameter = 10
Balloon.Inflated = True

Note the syntax of the code — the object (Balloon) followed by the property (.Color) followed by the assignment of the value (Red). You could change the color of the balloon from code by
repeating this statement and substituting a different value. Properties can also be set in the Properties window while you are designing your application.

A balloon's methods are invoked like this:

Balloon.Inflate
Balloon.Deflate
Balloon.Rise 5

The syntax is similar to the property — the object (a noun) followed by the method (a verb). In the third example, there is an additional item, called an argument, which denotes the distance to
rise. Some methods will have one or more arguments to further describe the action to be performed.

The balloon might respond to an event as follows:

Sub Balloon_Puncture()

http://msdn.microsoft.com/library/en-us/vbcon98/h...derstandingpropertiesmethodsevents.asp?frame=true (1 of 2) [11/17/2002 10:33:44 PM]


Understanding Properties, Methods and Events
Balloon.Deflate
Balloon.MakeNoise "Bang"
Balloon.Inflated = False
Balloon.Diameter = 1
End Sub

In this case, the code describes the balloon's behavior when a puncture event occurs: invoke the Deflate method, then invoke the MakeNoise method with an argument of "Bang" (the type of noise
to make). Since the balloon is no longer inflated, the Inflated property is set to False and the Diameter property is set to a new value.

While you can't actually program a balloon, you can program a Visual Basic form or control. As the programmer, you are in control. You decide which properties should be changed, methods
invoked or events responded to in order to achieve the desired appearance and behavior.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/h...derstandingpropertiesmethodsevents.asp?frame=true (2 of 2) [11/17/2002 10:33:44 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

MSDN Library GO
Advanced Search Visual Basic Concepts

Understanding Properties, Methods and Events

See Also

Up One Level Visual Basic forms and controls are objects which expose their own properties, methods and events. Properties can be thought of as an object's attributes, methods as its actions, and events
as its responses.
Understanding Properties, Methods and Events
Designing a Form An everyday object like a child's helium balloon also has properties, methods and events. A balloon's properties include visible attributes such as its height, diameter and color. Other properties
Clicking Buttons to Perform Actions describe its state (inflated or not inflated), or attributes that aren't visible such as its age. By definition, all balloons have these properties; the settings of these properties may differ from one
balloon to another.
Controls for Displaying and Entering Text
Controls That Present Choices to Users A balloon also has inherent methods or actions that it might perform. It has an inflate method (the action of filling it with helium), a deflate method (expelling its contents) and a rise method
(if you were to let go of it). Again, all balloons are capable of these methods.
Controls That Display Pictures and Graphics
Additional Controls
Balloons also have predefined responses to certain external events. For instance, a balloon would respond to the event of being punctured by deflating itself, or to the event of being released
Understanding Focus by rising into the air.

Setting the Tab Order


Menu Basics Figure 3.1 Objects have properties, respond to events, and perform methods

Prompting the User with Dialog Boxes

If you were able to program a balloon, the Visual Basic code might look like the following. To set the balloon's properties:

Balloon.Color = Red

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconunderstandingpropertiesmethodsevents.asp (1 of 2) [11/17/2002 10:33:46 PM]


Welcome to the MSDN Library
Balloon.Diameter = 10
Balloon.Inflated = True

Note the syntax of the code — the object (Balloon) followed by the property (.Color) followed by the assignment of the value (Red). You could change the color of the balloon from code by
repeating this statement and substituting a different value. Properties can also be set in the Properties window while you are designing your application.

A balloon's methods are invoked like this:

Balloon.Inflate
Balloon.Deflate
Balloon.Rise 5

The syntax is similar to the property — the object (a noun) followed by the method (a verb). In the third example, there is an additional item, called an argument, which denotes the distance
to rise. Some methods will have one or more arguments to further describe the action to be performed.

The balloon might respond to an event as follows:

Sub Balloon_Puncture()
Balloon.Deflate
Balloon.MakeNoise "Bang"
Balloon.Inflated = False
Balloon.Diameter = 1
End Sub

In this case, the code describes the balloon's behavior when a puncture event occurs: invoke the Deflate method, then invoke the MakeNoise method with an argument of "Bang" (the type of
noise to make). Since the balloon is no longer inflated, the Inflated property is set to False and the Diameter property is set to a new value.

While you can't actually program a balloon, you can program a Visual Basic form or control. As the programmer, you are in control. You decide which properties should be changed, methods
invoked or events responded to in order to achieve the desired appearance and behavior.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconunderstandingpropertiesmethodsevents.asp (2 of 2) [11/17/2002 10:33:46 PM]


Designing a Form

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

Visual Basic Concepts

Designing a Form

See Also

Form objects are the basic building blocks of a Visual Basic application, the actual windows with which a user interacts when they run the application. Forms have their own properties, events, and
methods with which you can control their appearance and behavior.

Figure 3.2 Forms and controls have their own properties, events, and methods

The first step in designing a form is to set its properties. You can set a form's properties at design time in the Properties window, or at run time by writing code.

Note You work with forms and controls, set their properties, and write code for their events at design time, which is any time you're building an application in the Visual Basic environment. Run
time is any time you are actually running the application and interacting with the application as the user would.

Setting Form Properties

Many of a form's properties affect its physical appearance. The Caption property determines the text that is shown in the form's title bar; the Icon property sets the icon that is displayed when a
form is minimized. The MaxButton and MinButton properties determine whether the form can be maximized or minimized. By changing the BorderStyle property, you can control the resizing
behavior of the form.

Height and Width properties determine the initial size of a form; Left and Top properties determine the form's location in relation to the upper left-hand corner of the screen. The WindowState
property can be set to start the form in a maximized, minimized, or normal state.

The Name property sets the name by which you will refer to the form in code. By default, when a form is first added to a project, its name is set to Form1, Form2, and so forth. It's a good idea to
set the Name property to something more meaningful, such as "frmEntry" for an order entry form.

The best way to familiarize yourself with the many form properties is to experiment. Change some of the properties of a form in the Properties window (Figure 3.3), then run the application to see
their effect. You can learn more about each property by selecting it and pressing F1 to view the context-sensitive Help.

Figure 3.3 The Properties window

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcondesigningform.asp?frame=true (1 of 2) [11/17/2002 10:33:51 PM]


Designing a Form

Form Events and Methods

As objects, forms can perform methods and respond to events.

The Resize event of a form is triggered whenever a form is resized, either by user interaction or through code. This allows you to perform actions such as moving or resizing controls on a form
when its dimensions have changed.

The Activate event occurs whenever a form becomes the active form; the Deactivate event occurs when another form or application becomes active. These events are convenient for initializing or
finalizing the form's behavior. For example, in the Activate event you might write code to highlight the text in a particular text box; in the Deactivate event you might save changes to a file or
database.

To make a form visible, you would invoke the Show method:

Form2.Show

Invoking the Show method has the same effect as setting a form's Visible property to True.

Many of a form's methods involve text or graphics. The Print, Line, Circle, and Refresh methods are useful for printing or drawing directly onto a form's surface. These methods and more are
discussed in "Working with Text and Graphics."

For More Information For additional information on forms, see "More About Forms" in "Creating a User Interface."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcondesigningform.asp?frame=true (2 of 2) [11/17/2002 10:33:51 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

MSDN Library GO
Advanced Search Visual Basic Concepts

Designing a Form

See Also

Up One Level Form objects are the basic building blocks of a Visual Basic application, the actual windows with which a user interacts when they run the application. Forms have their own properties, events,
and methods with which you can control their appearance and behavior.
Understanding Properties, Methods and Events
Designing a Form Figure 3.2 Forms and controls have their own properties, events, and methods
Clicking Buttons to Perform Actions
Controls for Displaying and Entering Text
Controls That Present Choices to Users
Controls That Display Pictures and Graphics
Additional Controls
Understanding Focus
Setting the Tab Order
Menu Basics
Prompting the User with Dialog Boxes

The first step in designing a form is to set its properties. You can set a form's properties at design time in the Properties window, or at run time by writing code.

Note You work with forms and controls, set their properties, and write code for their events at design time, which is any time you're building an application in the Visual Basic environment.
Run time is any time you are actually running the application and interacting with the application as the user would.

Setting Form Properties

Many of a form's properties affect its physical appearance. The Caption property determines the text that is shown in the form's title bar; the Icon property sets the icon that is displayed when
a form is minimized. The MaxButton and MinButton properties determine whether the form can be maximized or minimized. By changing the BorderStyle property, you can control the resizing
behavior of the form.

Height and Width properties determine the initial size of a form; Left and Top properties determine the form's location in relation to the upper left-hand corner of the screen. The WindowState
property can be set to start the form in a maximized, minimized, or normal state.

The Name property sets the name by which you will refer to the form in code. By default, when a form is first added to a project, its name is set to Form1, Form2, and so forth. It's a good idea

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondesigningform.asp (1 of 2) [11/17/2002 10:33:53 PM]


Welcome to the MSDN Library
to set the Name property to something more meaningful, such as "frmEntry" for an order entry form.

The best way to familiarize yourself with the many form properties is to experiment. Change some of the properties of a form in the Properties window (Figure 3.3), then run the application to
see their effect. You can learn more about each property by selecting it and pressing F1 to view the context-sensitive Help.

Figure 3.3 The Properties window

Form Events and Methods

As objects, forms can perform methods and respond to events.

The Resize event of a form is triggered whenever a form is resized, either by user interaction or through code. This allows you to perform actions such as moving or resizing controls on a form
when its dimensions have changed.

The Activate event occurs whenever a form becomes the active form; the Deactivate event occurs when another form or application becomes active. These events are convenient for initializing
or finalizing the form's behavior. For example, in the Activate event you might write code to highlight the text in a particular text box; in the Deactivate event you might save changes to a file
or database.

To make a form visible, you would invoke the Show method:

Form2.Show

Invoking the Show method has the same effect as setting a form's Visible property to True.

Many of a form's methods involve text or graphics. The Print, Line, Circle, and Refresh methods are useful for printing or drawing directly onto a form's surface. These methods and more are
discussed in "Working with Text and Graphics."

For More Information For additional information on forms, see "More About Forms" in "Creating a User Interface."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondesigningform.asp (2 of 2) [11/17/2002 10:33:53 PM]


Clicking Buttons to Perform Actions

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

Visual Basic Concepts

Clicking Buttons to Perform Actions

See Also

The easiest way to allow the user to interact with an application is to provide a button to click. You can use the command button control provided by Visual Basic, or you can create your own
"button" using an image control containing a graphic, such as an icon.

Using Command Buttons

Most Visual Basic applications have command buttons that allow the user to simply click them to perform actions. When the user chooses the button, it not only carries out the appropriate action,
it also looks as if it's being pushed in and released. Whenever the user clicks a button, the Click event procedure is invoked. You place code in the Click event procedure to perform any action you
choose.

There are many ways to choose a command button at run time:

● Use a mouse to click the button.

● Move the focus to the button by pressing the TAB key, and then choose the button by pressing the SPACEBAR or ENTER. (See "Understanding Focus" later in this chapter.)

● Press an access key (ALT+ the underlined letter) for a command button.

● Set the command button's Value property to True in code:

cmdClose.Value = True

● Invoke the command button's Click event in code:

cmdClose_Click

● If the command button is the default command button for the form, pressing ENTER chooses the button, even if you change the focus to a different control other than a command button. At design time, you specify a default command button by setting that
button's Default property to True.

● If the command button is the default Cancel button for the form, then pressing ESC chooses the button, even if you change the focus to another control. At design time, you specify a default Cancel button by setting that button's Cancel property to True.

All these actions cause Visual Basic to invoke the Click event procedure.

The Test Buttons Application

You use the Caption property to display text on the button to tell the user what the button does. In Figure 3.4, the Test Buttons example from the Controls sample application contains a command
button with its Caption property set to "Change Signal." (For a working version of this example, see Button.frm in the Controls.vbp sample application.)

Notice that 'S' is the access key for this button, denoted by an underline. Inserting an ampersand (&) in the text of the Caption property makes the character following it the access key for that
button (for example, Change &Signal).

Figure 3.4 Command button with a caption

When a user clicks the command button, the code in the command button's Click event procedure is executed. In the example, a different traffic light icon is displayed each time the button is

http://msdn.microsoft.com/library/en-us/vbcon98/ht...bconclickingbuttonstoperformactions.asp?frame=true (1 of 2) [11/17/2002 10:34:01 PM]


Clicking Buttons to Perform Actions

clicked.

For More Information For information on additional properties of the command button, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/ht...bconclickingbuttonstoperformactions.asp?frame=true (2 of 2) [11/17/2002 10:34:01 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

MSDN Library GO
Advanced Search Visual Basic Concepts

Clicking Buttons to Perform Actions

See Also

Up One Level The easiest way to allow the user to interact with an application is to provide a button to click. You can use the command button control provided by Visual Basic, or you can create your own
"button" using an image control containing a graphic, such as an icon.
Understanding Properties, Methods and Events
Designing a Form Using Command Buttons
Clicking Buttons to Perform Actions
Controls for Displaying and Entering Text Most Visual Basic applications have command buttons that allow the user to simply click them to perform actions. When the user chooses the button, it not only carries out the appropriate
action, it also looks as if it's being pushed in and released. Whenever the user clicks a button, the Click event procedure is invoked. You place code in the Click event procedure to perform any
Controls That Present Choices to Users action you choose.

Controls That Display Pictures and Graphics


Additional Controls There are many ways to choose a command button at run time:

Understanding Focus
Setting the Tab Order ● Use a mouse to click the button.

Move the focus to the button by pressing the TAB key, and then choose the button by pressing the SPACEBAR or ENTER. (See "Understanding Focus" later in this chapter.)
Menu Basics

● Press an access key (ALT+ the underlined letter) for a command button.

Prompting the User with Dialog Boxes ● Set the command button's Value property to True in code:

cmdClose.Value = True

● Invoke the command button's Click event in code:

cmdClose_Click

● If the command button is the default command button for the form, pressing ENTER chooses the button, even if you change the focus to a different control other than a command button. At design time, you specify a default command button by setting that
button's Default property to True.

● If the command button is the default Cancel button for the form, then pressing ESC chooses the button, even if you change the focus to another control. At design time, you specify a default Cancel button by setting that button's Cancel property to True.

All these actions cause Visual Basic to invoke the Click event procedure.

The Test Buttons Application

You use the Caption property to display text on the button to tell the user what the button does. In Figure 3.4, the Test Buttons example from the Controls sample application contains a
command button with its Caption property set to "Change Signal." (For a working version of this example, see Button.frm in the Controls.vbp sample application.)

Notice that 'S' is the access key for this button, denoted by an underline. Inserting an ampersand (&) in the text of the Caption property makes the character following it the access key for that
button (for example, Change &Signal).

Figure 3.4 Command button with a caption

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconclickingbuttonstoperformactions.asp (1 of 2) [11/17/2002 10:34:03 PM]


Welcome to the MSDN Library

When a user clicks the command button, the code in the command button's Click event procedure is executed. In the example, a different traffic light icon is displayed each time the button is
clicked.

For More Information For information on additional properties of the command button, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconclickingbuttonstoperformactions.asp (2 of 2) [11/17/2002 10:34:03 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

MSDN Library GO
Advanced Search Visual Basic Concepts

Controls for Displaying and Entering Text

See Also

Up One Level Label and text box controls are used to display or enter text. Use labels when you want your application to display text on a form, and text boxes when you want to allow the user to enter text.
Labels contain text that can only be read, while text boxes contain text that can be edited.
Using Labels to Display Text
Working with Text Boxes
To provide this feature Use this control

Text that can be edited by the user, for example an order entry field or a password box Text box

Text that is displayed only, for example to identify a field on a form or display instructions to the user Label

Labels and text boxes are discussed in the following sections:

● Using Labels to Display Text The basics of using the label control.

● Working with Text Boxes The basics of using text boxes.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondisplayingenteringtext.asp [11/17/2002 10:34:10 PM]


Using Labels to Display Text

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls for Displaying and Entering Text

Visual Basic Concepts

Using Labels to Display Text

See Also

A label control displays text that the user cannot directly change. You can use labels to identify controls, such as text boxes and scroll bars, that do not have their own Caption property. The actual
text displayed in a label is controlled by the Caption property, which can be set at design time in the Properties window or at run time by assigning it in code.

By default, the caption is the only visible part of the label control. However, if you set the BorderStyle property to 1 (which you can do at design time), the label appears with a border — giving it a
look similar to a text box. You can also change the appearance of the label by setting the BackColor, BackStyle, ForeColor, and Font properties.

Sizing a Label to Fit Its Contents

Single-line label captions can be specified at design time in the Properties window. But what if you want to enter a longer caption, or a caption that will change at run time? Labels have two
properties that help you size the controls to fit larger or smaller captions: AutoSize and WordWrap.

The AutoSize property determines if a control should be automatically resized to fit its contents. If set to True, the label grows horizontally to fit its contents, as shown in Figure 3.5.

Figure 3.5 AutoSize example

The WordWrap property causes the label to grow vertically to fit its contents, while retaining the same width, as shown in Figure 3.6. For a working version of this example, see Wordwrap.frm in
the Controls.vbp sample application.

Figure 3.6 WordWrap example

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconusinglabels.asp?frame=true (1 of 2) [11/17/2002 10:34:13 PM]


Using Labels to Display Text

Note If you run the AutoSize example from Controls.vbp, you'll notice that for the WordWrap example to actually work, both check boxes must be selected. This is because, for the label's
WordWrap property to take effect, AutoSize must be set to True. The width of the label is increased only if the width of a single word exceeds the current width of the control.

For More Information For additional information on the label control's properties, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconusinglabels.asp?frame=true (2 of 2) [11/17/2002 10:34:13 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls for Displaying and Entering Text

MSDN Library GO
Advanced Search Visual Basic Concepts

Using Labels to Display Text

See Also

Up One Level A label control displays text that the user cannot directly change. You can use labels to identify controls, such as text boxes and scroll bars, that do not have their own Caption property. The
actual text displayed in a label is controlled by the Caption property, which can be set at design time in the Properties window or at run time by assigning it in code.
Using Labels to Display Text
Working with Text Boxes By default, the caption is the only visible part of the label control. However, if you set the BorderStyle property to 1 (which you can do at design time), the label appears with a border — giving
it a look similar to a text box. You can also change the appearance of the label by setting the BackColor, BackStyle, ForeColor, and Font properties.

Sizing a Label to Fit Its Contents

Single-line label captions can be specified at design time in the Properties window. But what if you want to enter a longer caption, or a caption that will change at run time? Labels have two
properties that help you size the controls to fit larger or smaller captions: AutoSize and WordWrap.

The AutoSize property determines if a control should be automatically resized to fit its contents. If set to True, the label grows horizontally to fit its contents, as shown in Figure 3.5.

Figure 3.5 AutoSize example

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusinglabels.asp (1 of 3) [11/17/2002 10:34:15 PM]


Welcome to the MSDN Library

The WordWrap property causes the label to grow vertically to fit its contents, while retaining the same width, as shown in Figure 3.6. For a working version of this example, see Wordwrap.frm in
the Controls.vbp sample application.

Figure 3.6 WordWrap example

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusinglabels.asp (2 of 3) [11/17/2002 10:34:15 PM]


Welcome to the MSDN Library

Note If you run the AutoSize example from Controls.vbp, you'll notice that for the WordWrap example to actually work, both check boxes must be selected. This is because, for the label's
WordWrap property to take effect, AutoSize must be set to True. The width of the label is increased only if the width of a single word exceeds the current width of the control.

For More Information For additional information on the label control's properties, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusinglabels.asp (3 of 3) [11/17/2002 10:34:15 PM]


Working with Text Boxes

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls for Displaying and Entering Text

Visual Basic Concepts

Working with Text Boxes

See Also

Text boxes are versatile controls that can be used to get input from the user or to display text. Text boxes should not be used to display text that you don't want the user to change, unless you've
set the Locked property to True.

The actual text displayed in a text box is controlled by the Text property. It can be set in three different ways: at design time in the Property window, at run time by setting it in code, or by input
from the user at run time. The current contents of a text box can be retrieved at run time by reading the Text property.

Multiple-Line Text Boxes and Word Wrap

By default, a text box displays a single line of text and does not display scroll bars. If the text is longer than the available space, only part of the text will be visible. The look and behavior of a text
box can be changed by setting two properties, MultiLine and ScrollBars, which are available only at design time.

Note The ScrollBars property should not be confused with scroll bar controls, which are not attached to text boxes and have their own set of properties.

Setting MultiLine to True enables a text box to accept or display multiple lines of text at run time. A multiple-line text box automatically manages word wrap as long as there is no horizontal scroll
bar. The ScrollBars property is set to 0-None by default. Automatic word wrap saves the user the trouble of inserting line breaks at the end of lines. When a line of text is longer than what can be
displayed on a line, the text box wraps the text to the next line.

Line breaks cannot be entered in the Properties window at design time. Within a procedure, you create a line break by inserting a carriage return followed by a linefeed (ANSI characters 13 and
10). You can also use the constant vbCrLf to insert a carriage return/linefeed combination. For example, the following event procedure puts two lines of text into a multiple-line text box (Text1)
when the form is loaded:

Sub Form_Load ()
Text1.Text = "Here are two lines" _
& vbCrLf & "in a text box"
End Sub

Working with Text in a Text Box

You can control the insertion point and selection behavior in a text box with the SelStart, SelLength and SelText properties. These properties are only available at run time.

When a text box first receives the focus, the default insertion point or cursor position within the text box is to the left of any existing text. It can be moved by the user from the keyboard or with
the mouse. If the text box loses and then regains the focus, the insertion point will be wherever the user last placed it.

In some cases, this behavior can be disconcerting to the user. In a word processing application, the user might expect new characters to appear after any existing text. In a data entry application,
the user might expect their typing to replace any existing entry. The SelStart and SelLength properties allow you to modify the behavior to suit your purpose.

The SelStart property is a number that indicates the insertion point within the string of text, with 0 being the left-most position. If the SelStart property is set to a value equal to or greater than
the number of characters in the text box, the insertion point will be placed after the last character, as shown in Figure 3.7. For a working version of this example, see Text.frm in the Controls.vbp
sample application.

Figure 3.7 Insertion point example

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconworkingwithtextbox.asp?frame=true (1 of 3) [11/17/2002 10:34:19 PM]


Working with Text Boxes

The SelLength property is a numeric value that sets the width of the insertion point. Setting the SelLength to a number greater than 0 causes that number of characters to be selected and
highlighted, starting from the current insertion point. Figure 3.8 shows the selection behavior.

Figure 3.8 Selection example

If the user starts typing while a block of text is selected, the selected text will be replaced. In some cases, you might want to replace a text selection with new text by using a paste command. The
SelText property is a string of text that you can assign at run time to replace the current selection. If no text is selected, SelText will insert its text at the current insertion point.

For More Information For additional information on the text box control's properties, see "Using Visual Basic's Standard Controls."

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconworkingwithtextbox.asp?frame=true (2 of 3) [11/17/2002 10:34:19 PM]


Working with Text Boxes

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconworkingwithtextbox.asp?frame=true (3 of 3) [11/17/2002 10:34:19 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls for Displaying and Entering Text

MSDN Library GO
Advanced Search Visual Basic Concepts

Working with Text Boxes

See Also

Up One Level Text boxes are versatile controls that can be used to get input from the user or to display text. Text boxes should not be used to display text that you don't want the user to change, unless
you've set the Locked property to True.
Using Labels to Display Text
Working with Text Boxes The actual text displayed in a text box is controlled by the Text property. It can be set in three different ways: at design time in the Property window, at run time by setting it in code, or by
input from the user at run time. The current contents of a text box can be retrieved at run time by reading the Text property.

Multiple-Line Text Boxes and Word Wrap

By default, a text box displays a single line of text and does not display scroll bars. If the text is longer than the available space, only part of the text will be visible. The look and behavior of a
text box can be changed by setting two properties, MultiLine and ScrollBars, which are available only at design time.

Note The ScrollBars property should not be confused with scroll bar controls, which are not attached to text boxes and have their own set of properties.

Setting MultiLine to True enables a text box to accept or display multiple lines of text at run time. A multiple-line text box automatically manages word wrap as long as there is no horizontal
scroll bar. The ScrollBars property is set to 0-None by default. Automatic word wrap saves the user the trouble of inserting line breaks at the end of lines. When a line of text is longer than what
can be displayed on a line, the text box wraps the text to the next line.

Line breaks cannot be entered in the Properties window at design time. Within a procedure, you create a line break by inserting a carriage return followed by a linefeed (ANSI characters 13 and
10). You can also use the constant vbCrLf to insert a carriage return/linefeed combination. For example, the following event procedure puts two lines of text into a multiple-line text box (Text1)
when the form is loaded:

Sub Form_Load ()
Text1.Text = "Here are two lines" _
& vbCrLf & "in a text box"
End Sub

Working with Text in a Text Box

You can control the insertion point and selection behavior in a text box with the SelStart, SelLength and SelText properties. These properties are only available at run time.

When a text box first receives the focus, the default insertion point or cursor position within the text box is to the left of any existing text. It can be moved by the user from the keyboard or
with the mouse. If the text box loses and then regains the focus, the insertion point will be wherever the user last placed it.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconworkingwithtextbox.asp (1 of 3) [11/17/2002 10:34:21 PM]


Welcome to the MSDN Library
In some cases, this behavior can be disconcerting to the user. In a word processing application, the user might expect new characters to appear after any existing text. In a data entry
application, the user might expect their typing to replace any existing entry. The SelStart and SelLength properties allow you to modify the behavior to suit your purpose.

The SelStart property is a number that indicates the insertion point within the string of text, with 0 being the left-most position. If the SelStart property is set to a value equal to or greater than
the number of characters in the text box, the insertion point will be placed after the last character, as shown in Figure 3.7. For a working version of this example, see Text.frm in the
Controls.vbp sample application.

Figure 3.7 Insertion point example

The SelLength property is a numeric value that sets the width of the insertion point. Setting the SelLength to a number greater than 0 causes that number of characters to be selected and
highlighted, starting from the current insertion point. Figure 3.8 shows the selection behavior.

Figure 3.8 Selection example

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconworkingwithtextbox.asp (2 of 3) [11/17/2002 10:34:21 PM]


Welcome to the MSDN Library

If the user starts typing while a block of text is selected, the selected text will be replaced. In some cases, you might want to replace a text selection with new text by using a paste command.
The SelText property is a string of text that you can assign at run time to replace the current selection. If no text is selected, SelText will insert its text at the current insertion point.

For More Information For additional information on the text box control's properties, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconworkingwithtextbox.asp (3 of 3) [11/17/2002 10:34:21 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

MSDN Library GO
Advanced Search Visual Basic Concepts

Controls That Present Choices to Users

See Also

Up One Level Most applications need to present choices to their users, ranging from a simple yes/no option to selecting from a list containing hundreds of possibilities. Visual Basic includes several standard
controls that are useful for presenting choices. The following table summarizes these controls and their appropriate uses.
Selecting Individual Options with Check Boxes
Grouping Options with Option Buttons
Using List Boxes and Combo Boxes
To provide this feature Use this control

Using Scroll Bars as Input Devices A small set of choices from which a user can choose one or more options. Check boxes

A small set of options from which a user can choose just one. Option buttons (use frames if additional groups are needed)

A scrollable list of choices from which the user can choose. List box

A scrollable list of choices along with a text edit field. The user can either choose from the list or type a choice in the edit field. Combo box

Check boxes, option buttons, list boxes, and combo boxes are discussed in the following sections:

● Selecting Individual Options with Check Boxes The basics of using the check box control.

● Grouping Options with Option Buttons The basics of using the option button control.

● Using List Boxes and Combo Boxes An introduction to the list box and combo box controls.

● Using Scroll Bars as Input Devices A brief introduction to the scroll bar control.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcontrolsthatpresentchoicestousers.asp [11/17/2002 10:34:43 PM]


Selecting Individual Options with Check Boxes

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Present Choices to Users

Visual Basic Concepts

Selecting Individual Options with Check Boxes

See Also

A check box indicates whether a particular condition is on or off. You use check boxes in an application to give users true/false or yes/no options. Because check boxes work independently of each
other, a user can select any number of check boxes at the same time. For example in Figure 3.9, Bold and Italic can both be checked.

Figure 3.9 Check boxes

The Check Box Application

The Check Box example uses a check box to determine whether the text is displayed in regular or italic font. For a working version of this example, see Check.frm in the Controls.vbp sample
application.

The application has a text box, a label, a command button, and two check boxes, as shown in Figure 3.10.

Figure 3.10 Check box example

The following table lists the property settings for the objects in the application.

Object Property Setting

Form Name frmCheck


Caption Check Box Example

Text box Name txtDisplay


Text Some sample text

First Check box Name chkBold


Caption &Bold

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconselectingindividualoptions.asp?frame=true (1 of 2) [11/17/2002 10:34:47 PM]


Selecting Individual Options with Check Boxes

Second Check box Name chkItalic


Caption &Italic

Command button Name cmdClose


Caption &Close

When you check Bold or Italic, the check box's Value property is set to 1; when unchecked, its Value property is set to 0. The default Value is 0, so unless you change Value, the check box will be
unchecked when it is first displayed. You can use the constants vbChecked and vbUnchecked to represent the values 1 and 0.

Events in the Check Box Application

The Click event for the check box occurs as soon as you click the box. This event procedure tests to see whether the check box has been selected (that is, if its Value = vbChecked). If so, the text
is converted to bold or italic by setting the Bold or Italic properties of the Font object returned by the Font property of the text box.

Private Sub chkBold_Click ()


If ChkBold.Value = vbChecked Then ' If checked.
txtDisplay.Font.Bold = True
Else ' If not checked.
txtDisplay.Font.Bold = False
End If
End Sub

Private Sub chkItalic_Click ()


If ChkItalic.Value = vbChecked Then ' If checked.
txtDisplay.Font.Italic = True
Else ' If not checked.
txtDisplay.Font.Italic = False
End If
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconselectingindividualoptions.asp?frame=true (2 of 2) [11/17/2002 10:34:47 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Present Choices to Users

MSDN Library GO
Advanced Search Visual Basic Concepts

Selecting Individual Options with Check Boxes

See Also

Up One Level A check box indicates whether a particular condition is on or off. You use check boxes in an application to give users true/false or yes/no options. Because check boxes work independently of
each other, a user can select any number of check boxes at the same time. For example in Figure 3.9, Bold and Italic can both be checked.
Selecting Individual Options with Check Boxes
Grouping Options with Option Buttons Figure 3.9 Check boxes
Using List Boxes and Combo Boxes
Using Scroll Bars as Input Devices

The Check Box Application

The Check Box example uses a check box to determine whether the text is displayed in regular or italic font. For a working version of this example, see Check.frm in the Controls.vbp sample
application.

The application has a text box, a label, a command button, and two check boxes, as shown in Figure 3.10.

Figure 3.10 Check box example

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconselectingindividualoptions.asp (1 of 2) [11/17/2002 10:34:49 PM]


Welcome to the MSDN Library

The following table lists the property settings for the objects in the application.

Object Property Setting

Form Name frmCheck


Caption Check Box Example

Text box Name txtDisplay


Text Some sample text

First Check box Name chkBold


Caption &Bold

Second Check box Name chkItalic


Caption &Italic

Command button Name cmdClose


Caption &Close

When you check Bold or Italic, the check box's Value property is set to 1; when unchecked, its Value property is set to 0. The default Value is 0, so unless you change Value, the check box will
be unchecked when it is first displayed. You can use the constants vbChecked and vbUnchecked to represent the values 1 and 0.

Events in the Check Box Application

The Click event for the check box occurs as soon as you click the box. This event procedure tests to see whether the check box has been selected (that is, if its Value = vbChecked). If so, the
text is converted to bold or italic by setting the Bold or Italic properties of the Font object returned by the Font property of the text box.

Private Sub chkBold_Click ()


If ChkBold.Value = vbChecked Then ' If checked.
txtDisplay.Font.Bold = True
Else ' If not checked.
txtDisplay.Font.Bold = False
End If
End Sub

Private Sub chkItalic_Click ()


If ChkItalic.Value = vbChecked Then ' If checked.
txtDisplay.Font.Italic = True
Else ' If not checked.
txtDisplay.Font.Italic = False
End If
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconselectingindividualoptions.asp (2 of 2) [11/17/2002 10:34:49 PM]


Grouping Options with Option Buttons

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Present Choices to Users

Visual Basic Concepts

Grouping Options with Option Buttons

See Also

Option buttons present a set of two or more choices to the user. Unlike check boxes, however, option buttons should always work as part of a group; selecting one option button immediately
clears all the other buttons in the group. Defining an option button group tells the user, "Here is a set of choices from which you can choose one and only one."

For example, in the option button group shown in Figure 3.11, the user can select one of three option buttons.

Figure 3.11 Selecting an option button

Creating Option Button Groups

All of the option buttons placed directly on a form (that is, not in a frame or picture box) constitute one group. If you want to create additional option button groups, you must place some of them
inside frames or picture boxes.

All the option buttons inside any given frame constitute a separate group, as do all the option buttons inside a picture box. When you create a separate group this way, always draw the frame or
picture box first, and then draw the option buttons on top of it. Figure 3.12 shows a form with two option button groups.

Figure 3.12 Option button groups

A user can select only one option button in the group when you draw option buttons in a frame.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcongroupingoptions.asp?frame=true (1 of 4) [11/17/2002 10:34:58 PM]


Grouping Options with Option Buttons

To group controls in a frame

1. Select the frame control from the toolbox and draw the frame on the form.

2. Select the option button control from the toolbox and draw the control within the frame.

3. Repeat step 2 for each additional option button you wish to add to the frame.

Drawing the frame first and then drawing each control on the frame allows you to move the frame and controls together. If you try to move existing controls onto a frame, the controls will not
move with the frame.

Note If you have existing controls that you want to group in a frame, you can select all the controls and cut and paste them into a frame or picture control.

Containers for Controls

While controls are independent objects, a certain parent and child relationship exists between forms and controls. Figure 3.12 demonstrates how option buttons can be contained within a form or
within a frame control.

To understand the concept of containers, you need to understand that all controls are children of the form on which they are drawn. In fact, most controls support the read-only Parent property,
which returns the form on which a control is located. Being a child affects the placement of a control on the parent form. The Left and Top properties of a control are relative to the parent form,
and controls cannot be moved outside the boundaries of the parent. Moving a container moves the controls as well, and the control's position relative to the container's Left and Top properties
does not change because the control moves with the container.

Selecting or Disabling Option Buttons

An option button can be selected by:

● Clicking it at run time with the mouse.

● Tabbing to the option button group and then using the arrow keys to select an option button within the group.

● Assigning its Value property to True in code:

optChoice.Value = True

● Using a shortcut key specified in the caption of a label.

To make a button the default in an option button group, set its Value property to True at design time. It remains selected until a user selects a different option button or code changes it.

To disable an option button, set its Enabled property to False. When the program is run it will appear dimmed, meaning that it is unavailable.

The Options Application

The form shown in Figure 3.13 uses option buttons to determine the processor type and operating system for a fictional computer. When the user selects a option button in either group, the
caption of the label is changed to reflect the current choices. For a working version of this example, see Options.frm in the Controls.vbp sample application.

Figure 3.13 Option button example

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcongroupingoptions.asp?frame=true (2 of 4) [11/17/2002 10:34:58 PM]


Grouping Options with Option Buttons

The following table lists the property settings for the objects in the application.

Object Property Setting

Label Name lblDisplay


Caption (Empty)

Command button Name cmdClose


Caption &Close

First option button Name opt486


Caption &486

Second option button Name opt586


Caption &Pentium

Value True

Third option button Name opt686


Caption P&entium Pro

Frame Name fraSystem


Caption &Operating System

Fourth option button Name optWin95


Caption Windows 95

Fifth option button Name optWinNT


Caption Windows NT

Value True

Events in the Options Application

The Options application responds to events as follows:

● The Click events for the first three option buttons assign a corresponding description to a form-level string variable, strComputer.

● The Click events for the last two option buttons assign a corresponding description to a second form-level variable, strSystem.

The key to this approach is the use of these two form-level variables, strComputer and strSystem. These variables contain different string values, depending on which option buttons were last
selected.

Each time a new option button is selected, the code in its Click event updates the appropriate variable:

Private Sub opt586_Click()


strComputer = "Pentium"
Call DisplayCaption
End Sub

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcongroupingoptions.asp?frame=true (3 of 4) [11/17/2002 10:34:58 PM]


Grouping Options with Option Buttons

It then calls a sub procedure, called DisplayCaption, that concatenates the two variables and updates the label's Caption property:

Sub DisplayCaption()
lblDisplay.Caption = "You selected a " & _
strComputer & " running " & strSystem
End Sub

A sub procedure is used because the procedure of updating the Caption property is essentially the same for all five option buttons, only the value of the variables change from one instance to the
next. This saves you from having to repeat the same code in each of the Click events.

For More Information Variables and sub procedures are discussed in detail in "Programming Fundamentals."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcongroupingoptions.asp?frame=true (4 of 4) [11/17/2002 10:34:58 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Present Choices to Users

MSDN Library GO
Advanced Search Visual Basic Concepts

Grouping Options with Option Buttons

See Also

Up One Level Option buttons present a set of two or more choices to the user. Unlike check boxes, however, option buttons should always work as part of a group; selecting one option button immediately
clears all the other buttons in the group. Defining an option button group tells the user, "Here is a set of choices from which you can choose one and only one."
Selecting Individual Options with Check Boxes
Grouping Options with Option Buttons For example, in the option button group shown in Figure 3.11, the user can select one of three option buttons.
Using List Boxes and Combo Boxes
Using Scroll Bars as Input Devices Figure 3.11 Selecting an option button

Creating Option Button Groups

All of the option buttons placed directly on a form (that is, not in a frame or picture box) constitute one group. If you want to create additional option button groups, you must place some of
them inside frames or picture boxes.

All the option buttons inside any given frame constitute a separate group, as do all the option buttons inside a picture box. When you create a separate group this way, always draw the frame
or picture box first, and then draw the option buttons on top of it. Figure 3.12 shows a form with two option button groups.

Figure 3.12 Option button groups

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcongroupingoptions.asp (1 of 4) [11/17/2002 10:35:00 PM]


Welcome to the MSDN Library

A user can select only one option button in the group when you draw option buttons in a frame.

To group controls in a frame

1. Select the frame control from the toolbox and draw the frame on the form.

2. Select the option button control from the toolbox and draw the control within the frame.

3. Repeat step 2 for each additional option button you wish to add to the frame.

Drawing the frame first and then drawing each control on the frame allows you to move the frame and controls together. If you try to move existing controls onto a frame, the controls will not
move with the frame.

Note If you have existing controls that you want to group in a frame, you can select all the controls and cut and paste them into a frame or picture control.

Containers for Controls

While controls are independent objects, a certain parent and child relationship exists between forms and controls. Figure 3.12 demonstrates how option buttons can be contained within a form
or within a frame control.

To understand the concept of containers, you need to understand that all controls are children of the form on which they are drawn. In fact, most controls support the read-only Parent
property, which returns the form on which a control is located. Being a child affects the placement of a control on the parent form. The Left and Top properties of a control are relative to the
parent form, and controls cannot be moved outside the boundaries of the parent. Moving a container moves the controls as well, and the control's position relative to the container's Left and
Top properties does not change because the control moves with the container.

Selecting or Disabling Option Buttons

An option button can be selected by:

● Clicking it at run time with the mouse.

● Tabbing to the option button group and then using the arrow keys to select an option button within the group.

● Assigning its Value property to True in code:

optChoice.Value = True

● Using a shortcut key specified in the caption of a label.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcongroupingoptions.asp (2 of 4) [11/17/2002 10:35:00 PM]


Welcome to the MSDN Library

To make a button the default in an option button group, set its Value property to True at design time. It remains selected until a user selects a different option button or code changes it.

To disable an option button, set its Enabled property to False. When the program is run it will appear dimmed, meaning that it is unavailable.

The Options Application

The form shown in Figure 3.13 uses option buttons to determine the processor type and operating system for a fictional computer. When the user selects a option button in either group, the
caption of the label is changed to reflect the current choices. For a working version of this example, see Options.frm in the Controls.vbp sample application.

Figure 3.13 Option button example

The following table lists the property settings for the objects in the application.

Object Property Setting

Label Name lblDisplay


Caption (Empty)

Command button Name cmdClose


Caption &Close

First option button Name opt486


Caption &486

Second option button Name opt586


Caption &Pentium

Value True

Third option button Name opt686


Caption P&entium Pro

Frame Name fraSystem


Caption &Operating System

Fourth option button Name optWin95


Caption Windows 95

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcongroupingoptions.asp (3 of 4) [11/17/2002 10:35:00 PM]


Welcome to the MSDN Library
Fifth option button Name optWinNT
Caption Windows NT

Value True

Events in the Options Application

The Options application responds to events as follows:

● The Click events for the first three option buttons assign a corresponding description to a form-level string variable, strComputer.

● The Click events for the last two option buttons assign a corresponding description to a second form-level variable, strSystem.

The key to this approach is the use of these two form-level variables, strComputer and strSystem. These variables contain different string values, depending on which option buttons were
last selected.

Each time a new option button is selected, the code in its Click event updates the appropriate variable:

Private Sub opt586_Click()


strComputer = "Pentium"
Call DisplayCaption
End Sub

It then calls a sub procedure, called DisplayCaption, that concatenates the two variables and updates the label's Caption property:

Sub DisplayCaption()
lblDisplay.Caption = "You selected a " & _
strComputer & " running " & strSystem
End Sub

A sub procedure is used because the procedure of updating the Caption property is essentially the same for all five option buttons, only the value of the variables change from one instance to
the next. This saves you from having to repeat the same code in each of the Click events.

For More Information Variables and sub procedures are discussed in detail in "Programming Fundamentals."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcongroupingoptions.asp (4 of 4) [11/17/2002 10:35:00 PM]


Using List Boxes and Combo Boxes

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Present Choices to Users

Visual Basic Concepts

Using List Boxes and Combo Boxes

See Also

List boxes and combo boxes present a list of choices to the user. By default, the choices are displayed vertically in a single column, although you can set up multiple columns as well. If the number
of items exceeds what can be displayed in the combo box or list box, scroll bars automatically appear on the control. The user can then scroll up and down or left to right through the list. Figure
3.14 shows a single-column list box.

Figure 3.14 Single-column list box

A combo box control combines the features of a text box and a list box. This control allows the user to select either by typing text into the combo box or by selecting an item from its list. Figure
3.15 shows a combo box.

Figure 3.15 Combo box

In contrast to some other controls that contain a single value; for example the label's Caption property or the text box's Text property, list boxes and combo boxes contain multiple values or a
collection of values. They have built-in methods for adding, removing and retrieving values from their collections at run time. To add several items to a list box named List1, the code would look
like this:

List1.AddItem "Paris"
List1.AddItem "New York"
List1.AddItem "San Francisco"

List boxes and combo boxes are an effective way to present a large number of choices to the user in a limited amount of space.

For More Information For additional information on the list box and combo box controls, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconusinglistcombobox.asp?frame=true [11/17/2002 10:35:05 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Present Choices to Users

MSDN Library GO
Advanced Search Visual Basic Concepts

Using List Boxes and Combo Boxes

See Also

Up One Level List boxes and combo boxes present a list of choices to the user. By default, the choices are displayed vertically in a single column, although you can set up multiple columns as well. If the
number of items exceeds what can be displayed in the combo box or list box, scroll bars automatically appear on the control. The user can then scroll up and down or left to right through the
Selecting Individual Options with Check Boxes list. Figure 3.14 shows a single-column list box.

Grouping Options with Option Buttons


Using List Boxes and Combo Boxes Figure 3.14 Single-column list box

Using Scroll Bars as Input Devices

A combo box control combines the features of a text box and a list box. This control allows the user to select either by typing text into the combo box or by selecting an item from its list.
Figure 3.15 shows a combo box.

Figure 3.15 Combo box

In contrast to some other controls that contain a single value; for example the label's Caption property or the text box's Text property, list boxes and combo boxes contain multiple values or a
collection of values. They have built-in methods for adding, removing and retrieving values from their collections at run time. To add several items to a list box named List1, the code would
look like this:

List1.AddItem "Paris"

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusinglistcombobox.asp (1 of 2) [11/17/2002 10:35:07 PM]


Welcome to the MSDN Library
List1.AddItem "New York"
List1.AddItem "San Francisco"

List boxes and combo boxes are an effective way to present a large number of choices to the user in a limited amount of space.

For More Information For additional information on the list box and combo box controls, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusinglistcombobox.asp (2 of 2) [11/17/2002 10:35:07 PM]


Using Scroll Bars as Input Devices

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Present Choices to Users

Visual Basic Concepts

Using Scroll Bars as Input Devices

See Also

Although scroll bars are often tied to text boxes or windows, you'll sometimes see them used as input devices. Because these controls can indicate the current position on a scale, scroll bar
controls can be used individually to control program input — for example, to control the sound volume or to adjust the colors in a picture. The HScrollBar (horizontal) and VScrollBar (vertical)
controls operate independently from other controls and have their own set of events, properties, and methods. Scroll bar controls are not the same as the built-in scroll bars that are attached to
text boxes, list boxes, combo boxes, or MDI forms (text boxes and MDI forms have a ScrollBars property to add or remove scroll bars that are attached to the control).

Windows interface guidelines now suggest using slider controls as input devices instead of scroll bars. Examples of slider controls can be seen in the Windows 95/98 control panel. A slider control
of this type is included in the Professional and Enterprise editions of Visual Basic.

For More Information For additional information on scroll bar controls, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconusingscrollbars.asp?frame=true [11/17/2002 10:35:11 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Present Choices to Users

MSDN Library GO
Advanced Search Visual Basic Concepts

Using Scroll Bars as Input Devices

See Also

Up One Level Although scroll bars are often tied to text boxes or windows, you'll sometimes see them used as input devices. Because these controls can indicate the current position on a scale, scroll bar
controls can be used individually to control program input — for example, to control the sound volume or to adjust the colors in a picture. The HScrollBar (horizontal) and VScrollBar (vertical)
Selecting Individual Options with Check Boxes controls operate independently from other controls and have their own set of events, properties, and methods. Scroll bar controls are not the same as the built-in scroll bars that are attached
to text boxes, list boxes, combo boxes, or MDI forms (text boxes and MDI forms have a ScrollBars property to add or remove scroll bars that are attached to the control).
Grouping Options with Option Buttons
Using List Boxes and Combo Boxes Windows interface guidelines now suggest using slider controls as input devices instead of scroll bars. Examples of slider controls can be seen in the Windows 95/98 control panel. A slider
Using Scroll Bars as Input Devices control of this type is included in the Professional and Enterprise editions of Visual Basic.

For More Information For additional information on scroll bar controls, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusingscrollbars.asp [11/17/2002 10:35:14 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

MSDN Library GO
Advanced Search Visual Basic Concepts

Controls That Display Pictures and Graphics

See Also

Up One Level Because Windows is a graphical user interface, it's important to have a way to display graphical images in your application's interface. Visual Basic includes four controls that make it easy to
work with graphics: the picture box control, the image control, the shape control, and the line control.
Working With the Picture Box Control
Lightweight Graphical Controls The image, shape and line controls are sometimes referred to as "lightweight" graphical controls. They require less system resources and consequently display somewhat faster than the picture
The Images Application box control; they contain a subset of the properties, methods and events available in the picture box. Each is best suited for a particular purpose.

To provide this feature Use this control

A container for other controls. Picture box

Printing or graphics methods. Picture box

Displaying a picture. Image control or picture box

Displaying a simple graphical element Shape or line control

Picture boxes, image controls, shape controls, and line controls are discussed in the following sections:

● Working with the Picture Box Control The basics of using the picture box control.

● Lightweight Graphical Controls The basics of using the image, shape, and line controls.

● The Images Application An example of using the graphical controls.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondisplayingpicturesgraphics.asp [11/17/2002 10:35:26 PM]


Working With the Picture Box Control

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Display Pictures and Graphics

Visual Basic Concepts

Working With the Picture Box Control

See Also

The primary use for the picture box control is to display a picture to the user. The actual picture that is displayed is determined by the Picture property. The Picture property contains the file name
(and optional path) for the picture file that you wish to display.

Note Form objects also have a Picture property that can be set to display a picture directly on the form's background.

To display or replace a picture at run time, you can use the LoadPicture function to set the Picture property. You supply the name (and optional path) for the picture and the LoadPicture function
handles the details of loading and displaying it:

picMain.Picture = LoadPicture("VANGOGH.gif")

The picture box control has an AutoSize property that, when set to True, causes the picture box to resize automatically to match the dimensions of its contents. Take extra care in designing your
form if you plan on using a picture box with the AutoSize enabled. The picture will resize without regard to other controls on the form, possibly causing unexpected results, such as covering up
other controls. It's a good idea to test this by loading each of the pictures at design time.

Using the Picture Box as a Container

The picture box control can also be used as a container for other controls. Like the frame control, you can draw other controls on top of the picture box. The contained controls move with the
picture box and their Top and Left properties will be relative to the picture box rather than the form.

A common use for the picture box container is as a toolbar or status bar. You can place image controls on it to act as buttons, or add labels to display status messages. By setting the Align
property to Top, Bottom, Left, or Right, the picture box will "stick" to the edge of the form. Figure 3.16 shows a picture box with its Align property set to Bottom. It contains two label controls
which could be used to display status messages.

Figure 3.16 Picture box used as a status bar

Other Uses for the Picture Box

The picture box control has several methods that make it useful for other purposes. Think of the picture box as a blank canvas upon which you can paint, draw or print. A single control can be
used to display text, graphics or even simple animation.

The Print method allows you to output text to the picture box control just as you would to a printer. Several font properties are available to control the characteristics of text output by the Print
method; the Cls method can be used to erase the output.

Circle, Line, Point and Pset methods may be used to draw graphics on the picture box. Properties such as DrawWidth, FillColor, and FillStyle allow you to customize the appearance of the graphics.

Animation can be created using the PaintPicture method by moving images within the picture control and rapidly changing between several different images.

For More Information For additional information on the picture box control, see "Using Visual Basic's Standard Controls."

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconusingpicturebox.asp?frame=true (1 of 2) [11/17/2002 10:35:31 PM]


Working With the Picture Box Control

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconusingpicturebox.asp?frame=true (2 of 2) [11/17/2002 10:35:31 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Display Pictures and Graphics

MSDN Library GO
Advanced Search Visual Basic Concepts

Working With the Picture Box Control

See Also

The primary use for the picture box control is to display a picture to the user. The actual picture that is displayed is determined by the Picture property. The Picture property contains the file
Up One Level name (and optional path) for the picture file that you wish to display.
Working With the Picture Box Control
Lightweight Graphical Controls Note Form objects also have a Picture property that can be set to display a picture directly on the form's background.

The Images Application


To display or replace a picture at run time, you can use the LoadPicture function to set the Picture property. You supply the name (and optional path) for the picture and the LoadPicture
function handles the details of loading and displaying it:

picMain.Picture = LoadPicture("VANGOGH.gif")

The picture box control has an AutoSize property that, when set to True, causes the picture box to resize automatically to match the dimensions of its contents. Take extra care in designing
your form if you plan on using a picture box with the AutoSize enabled. The picture will resize without regard to other controls on the form, possibly causing unexpected results, such as
covering up other controls. It's a good idea to test this by loading each of the pictures at design time.

Using the Picture Box as a Container

The picture box control can also be used as a container for other controls. Like the frame control, you can draw other controls on top of the picture box. The contained controls move with the
picture box and their Top and Left properties will be relative to the picture box rather than the form.

A common use for the picture box container is as a toolbar or status bar. You can place image controls on it to act as buttons, or add labels to display status messages. By setting the Align
property to Top, Bottom, Left, or Right, the picture box will "stick" to the edge of the form. Figure 3.16 shows a picture box with its Align property set to Bottom. It contains two label controls
which could be used to display status messages.

Figure 3.16 Picture box used as a status bar

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusingpicturebox.asp (1 of 2) [11/17/2002 10:35:56 PM]


Welcome to the MSDN Library

Other Uses for the Picture Box

The picture box control has several methods that make it useful for other purposes. Think of the picture box as a blank canvas upon which you can paint, draw or print. A single control can be
used to display text, graphics or even simple animation.

The Print method allows you to output text to the picture box control just as you would to a printer. Several font properties are available to control the characteristics of text output by the Print
method; the Cls method can be used to erase the output.

Circle, Line, Point and Pset methods may be used to draw graphics on the picture box. Properties such as DrawWidth, FillColor, and FillStyle allow you to customize the appearance of the
graphics.

Animation can be created using the PaintPicture method by moving images within the picture control and rapidly changing between several different images.

For More Information For additional information on the picture box control, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusingpicturebox.asp (2 of 2) [11/17/2002 10:35:56 PM]


Lightweight Graphical Controls

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Display Pictures and Graphics

Visual Basic Concepts

Lightweight Graphical Controls

See Also

The image, shape and line controls are considered to be lightweight controls; that is, they support only a subset of the properties, methods, and events found in the picture box. Because of this,
they typically require less system resources and load faster than the picture box control.

Using Image Controls Instead of Picture Boxes

The image control is similar to the picture box control but is used only for displaying pictures. It doesn't have the ability to act as a container for other controls, and it doesn't support the advanced
methods of the picture box.

Pictures are loaded into the image control just as they are in the picture box: at design time, set the Picture property to a file name and path; at run time, use the LoadPicture function.

The sizing behavior of the image control differs from that of the picture box. It has a Stretch property while the picture box has an AutoSize property. Setting the AutoSize property to True causes
a picture box to resize to the dimensions of the picture; setting it to False causes the picture to be cropped (only a portion of the picture is visible). When set to False (the default), the Stretch
property of the image control causes it to resize to the dimensions of the picture. Setting the Stretch property to True causes the picture to resize to the size of the image control, which may cause
the picture to appear distorted.

For More Information For additional information on the image control, see "Using Visual Basic's Standard Controls."

Using an Image Control to Create Your Own Buttons

An image control also recognizes the Click event, so you can use this control anywhere you'd use a command button. This is a convenient way to create a button with a picture instead of a caption.
Grouping several image controls together horizontally across the top of the screen — usually within a picture box — allows you to create a toolbar in your application.

For instance, the Test Buttons example shows an image control that users can choose like they choose a command button. When the form is first displayed, the control displays one of three traffic
icons from the Icon Library included with Visual Basic. Each time the image control is clicked, a different icon is displayed. (For a working version of this example, see Button.frm in the
Controls.vbp sample application.)

If you inspect the form at design time, you will see that it actually contains all three icons "stacked" on top of each other. By changing the Visible property of the top image control to False, you
allow the next image (with its Visible property set to True) to appear on top.

Figure 3.17 shows the image control with one of the traffic icons (Trffc10a.ico).

Figure 3.17 Image control with a traffic icon

To create a border around the image control, set the BorderStyle property to 1-Fixed Single.

Note Unlike command buttons, image controls do not appear pushed in when clicked. This means that unless you change the bitmap in the MouseDown event, there is no visual cue to the user
that the "button" is being pushed.

For More Information For information on displaying a graphic image in an image control, see "Using Visual Basic's Standard Controls."

Using Shape and Line Controls

Shape and line controls are useful for drawing graphical elements on the surface of a form. These controls don't support any events; they are strictly for decorative purposes.

Several properties are provided to control the appearance of the shape control. By setting the Shape property, it can be displayed as a rectangle, square, oval, circle, rounded rectangle, or
rounded square. The BorderColor and FillColor properties can be set to change the color; the BorderStyle, BorderWidth, FillStyle, and DrawMode properties control how the shape is drawn.

The line control is similar to the shape control but can only be used to draw straight lines.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconlightweightcontrols.asp?frame=true (1 of 2) [11/17/2002 10:36:06 PM]


Lightweight Graphical Controls

For More Information For additional information on the shape and line controls, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconlightweightcontrols.asp?frame=true (2 of 2) [11/17/2002 10:36:06 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Display Pictures and Graphics

MSDN Library GO
Advanced Search Visual Basic Concepts

Lightweight Graphical Controls

See Also

Up One Level The image, shape and line controls are considered to be lightweight controls; that is, they support only a subset of the properties, methods, and events found in the picture box. Because of
this, they typically require less system resources and load faster than the picture box control.
Working With the Picture Box Control
Lightweight Graphical Controls Using Image Controls Instead of Picture Boxes
The Images Application
The image control is similar to the picture box control but is used only for displaying pictures. It doesn't have the ability to act as a container for other controls, and it doesn't support the
advanced methods of the picture box.

Pictures are loaded into the image control just as they are in the picture box: at design time, set the Picture property to a file name and path; at run time, use the LoadPicture function.

The sizing behavior of the image control differs from that of the picture box. It has a Stretch property while the picture box has an AutoSize property. Setting the AutoSize property to True
causes a picture box to resize to the dimensions of the picture; setting it to False causes the picture to be cropped (only a portion of the picture is visible). When set to False (the default), the
Stretch property of the image control causes it to resize to the dimensions of the picture. Setting the Stretch property to True causes the picture to resize to the size of the image control, which
may cause the picture to appear distorted.

For More Information For additional information on the image control, see "Using Visual Basic's Standard Controls."

Using an Image Control to Create Your Own Buttons

An image control also recognizes the Click event, so you can use this control anywhere you'd use a command button. This is a convenient way to create a button with a picture instead of a
caption. Grouping several image controls together horizontally across the top of the screen — usually within a picture box — allows you to create a toolbar in your application.

For instance, the Test Buttons example shows an image control that users can choose like they choose a command button. When the form is first displayed, the control displays one of three
traffic icons from the Icon Library included with Visual Basic. Each time the image control is clicked, a different icon is displayed. (For a working version of this example, see Button.frm in the
Controls.vbp sample application.)

If you inspect the form at design time, you will see that it actually contains all three icons "stacked" on top of each other. By changing the Visible property of the top image control to False, you
allow the next image (with its Visible property set to True) to appear on top.

Figure 3.17 shows the image control with one of the traffic icons (Trffc10a.ico).

Figure 3.17 Image control with a traffic icon

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconlightweightcontrols.asp (1 of 2) [11/17/2002 10:36:08 PM]


Welcome to the MSDN Library

To create a border around the image control, set the BorderStyle property to 1-Fixed Single.

Note Unlike command buttons, image controls do not appear pushed in when clicked. This means that unless you change the bitmap in the MouseDown event, there is no visual cue to the
user that the "button" is being pushed.

For More Information For information on displaying a graphic image in an image control, see "Using Visual Basic's Standard Controls."

Using Shape and Line Controls

Shape and line controls are useful for drawing graphical elements on the surface of a form. These controls don't support any events; they are strictly for decorative purposes.

Several properties are provided to control the appearance of the shape control. By setting the Shape property, it can be displayed as a rectangle, square, oval, circle, rounded rectangle, or
rounded square. The BorderColor and FillColor properties can be set to change the color; the BorderStyle, BorderWidth, FillStyle, and DrawMode properties control how the shape is drawn.

The line control is similar to the shape control but can only be used to draw straight lines.

For More Information For additional information on the shape and line controls, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconlightweightcontrols.asp (2 of 2) [11/17/2002 10:36:08 PM]


The Images Application

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Display Pictures and Graphics

Visual Basic Concepts

The Images Application

See Also

The form shown in Figure 3.18 uses four image controls, a shape control, a picture box, and a command button. When the user selects a playing card symbol, the shape control highlights the
symbol and a description is displayed in the picture box. For a working version of this example, see Images.frm in the Controls.vbp sample application.

Figure 3.18 Image and shape control example

The following table lists the property settings for the objects in the application.

Object Property Setting

Picture box Name picStatus


Align Bottom

First image control Name imgClub


Picture Spade.ico

Second image control Name imgDiamond


Picture Diamond.ico

Third image control Name imgHeart


Picture Heart.ico

Fourth image control Name imgSpade


Caption Spade.ico

Shape control Name shpCard


Shape 4 - Rounded Rectangle
BorderWidth 2

Height 735

Width 495

Command button Name cmdClose


Caption &Close

Events in the Images Application

The Images application responds to events as follows:

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcontheimagesapplication.asp?frame=true (1 of 2) [11/17/2002 10:36:15 PM]


The Images Application

● The Click event in each of the image controls sets the Left property of the shape control equal to its own Left property, moving the shape on top of the image.

● The Cls method of the picture box is invoked, clearing the current caption from the status bar.

● The Print method of the picture box is invoked, printing the new caption on the status bar.

The code in the image control Click event looks like this:

Private Sub imgHeart_Click()


shpCard.Left = imgClub.Left
picStatus.Cls
picStatus.Print "Selected: Club"
shpCard.Visible = True
End Sub

Note that the first line in the Click event code assigns a value (the Left property of the image control) to the Left property of the shape control using the = operator. The next two lines invoke
methods, so no operator is needed. In the third line, the value ("Selected: Club") is an argument to the Print method.

There is one more line of code in the application that is of interest; it is in the Form Load event.

shpCard.Visible = False

By setting the Visible property of the shape control to False, the shape control is hidden until the first image is clicked. The Visible property is set to True as the last step in the image control Click
event.

For More Information For additional information on properties, methods, and events see "Programming Fundamentals."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcontheimagesapplication.asp?frame=true (2 of 2) [11/17/2002 10:36:15 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus > Controls That Display Pictures and Graphics

MSDN Library GO
Advanced Search Visual Basic Concepts

The Images Application

See Also

Up One Level The form shown in Figure 3.18 uses four image controls, a shape control, a picture box, and a command button. When the user selects a playing card symbol, the shape control highlights the
symbol and a description is displayed in the picture box. For a working version of this example, see Images.frm in the Controls.vbp sample application.
Working With the Picture Box Control
Lightweight Graphical Controls Figure 3.18 Image and shape control example
The Images Application

The following table lists the property settings for the objects in the application.

Object Property Setting

Picture box Name picStatus


Align Bottom

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcontheimagesapplication.asp (1 of 2) [11/17/2002 10:36:17 PM]


Welcome to the MSDN Library
First image control Name imgClub
Picture Spade.ico

Second image control Name imgDiamond


Picture Diamond.ico

Third image control Name imgHeart


Picture Heart.ico

Fourth image control Name imgSpade


Caption Spade.ico

Shape control Name shpCard


Shape 4 - Rounded Rectangle
BorderWidth 2

Height 735

Width 495

Command button Name cmdClose


Caption &Close

Events in the Images Application

The Images application responds to events as follows:

● The Click event in each of the image controls sets the Left property of the shape control equal to its own Left property, moving the shape on top of the image.

● The Cls method of the picture box is invoked, clearing the current caption from the status bar.

● The Print method of the picture box is invoked, printing the new caption on the status bar.

The code in the image control Click event looks like this:

Private Sub imgHeart_Click()


shpCard.Left = imgClub.Left
picStatus.Cls
picStatus.Print "Selected: Club"
shpCard.Visible = True
End Sub

Note that the first line in the Click event code assigns a value (the Left property of the image control) to the Left property of the shape control using the = operator. The next two lines invoke
methods, so no operator is needed. In the third line, the value ("Selected: Club") is an argument to the Print method.

There is one more line of code in the application that is of interest; it is in the Form Load event.

shpCard.Visible = False

By setting the Visible property of the shape control to False, the shape control is hidden until the first image is clicked. The Visible property is set to True as the last step in the image control
Click event.

For More Information For additional information on properties, methods, and events see "Programming Fundamentals."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcontheimagesapplication.asp (2 of 2) [11/17/2002 10:36:17 PM]


Additional Controls

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

Visual Basic Concepts

Additional Controls

See Also

Several other standard controls are included in the Visual Basic toolbox. Some controls are useful for working with large amounts of data contained in an external database. Other controls can be
used to access the Windows file system. Still other controls defy categorization, but are useful nonetheless.

You can also use ActiveX controls, previously called custom or OLE controls, in a Visual Basic application in the same way that you use the standard controls. The Professional and Enterprise
editions of Visual Basic include several ActiveX controls as well as the capability to build your own controls. Additional ActiveX controls for just about any purpose imaginable are available for
purchase from numerous vendors.

For More Information For additional information on using ActiveX controls, see "Managing Projects."

Data Access Controls

In today's business, most information is stored in one or more central databases. Visual Basic includes several data access controls for accessing most popular databases, including Microsoft
Access and SQL Server.

● The ADO Data control is used to connect to a database. Think of it as a pipeline between the database and the other controls on your form. Its properties, methods, and events allow you to navigate and manipulate external data from within your own application.

● The DataList control is similar to the list box control. When used in conjunction with an ADO Data control, it can be automatically filled with a list of data from a field in an external database.

● The DataCombo control is like a combination of the DataList control and a text box. The selected text in the text box portion can be edited, with the changes appearing in the underlying database.

● The DataGrid control displays data in a grid or table. When used in conjunction with an ADO Data control, it presents fully editable data from multiple fields in an external database.

● The Microsoft Hierarchical FlexGrid control is a unique control for presenting multiple views of data. Think of it as a combination of a grid and a tree or outline control. At run time, the user can rearrange columns and rows to provide different views of the data.

For More Information For additional information on data access controls, see "Using Visual Basic's Standard Controls." For more information on working with external data, see the Visual Basic
Data Access Guide.

File System Controls

Visual Basic includes three controls for adding file handling capabilities to your application. These controls are normally used together to provide a view of drives, directories and files; they have
special properties and events that tie them together.

● The DriveListBox control looks like a combo box. It provides a drop-down list of drives from which the user can select.

● The DirListBox is similar to a list box control, but with the built-in capability of displaying a list of directories in the currently selected drive.

● The FileListBox control also looks like a list box with a list of file names in a selected directory.

Note These controls are provided primarily for backward compatibility with applications created in earlier versions of Visual Basic. The common dialog control provides an easier method of
working with file access. For more information on common dialog control, see "Miscellaneous Controls" later in this chapter.

Miscellaneous Controls

Several other standard controls are included in Visual Basic. Each serves a unique purpose.

● The timer control can be used to create an event in your application at a recurring interval. This is useful for executing code without the need for user interaction.

● The OLE container control is an easy way to add capabilities like linking and embedding to your application. Through the OLE container control, you can provide access to the functionality of any OLE-enabled application such as Microsoft Excel, Word and many
others.

● The common dialog control adds built-in dialog boxes to your application for the selection of files, colors, fonts, and printing functions.

For More Information For additional information on any of the standard controls, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconadditionalcontrols.asp?frame=true [11/17/2002 10:36:25 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

MSDN Library GO
Advanced Search Visual Basic Concepts

Additional Controls

See Also

Up One Level Several other standard controls are included in the Visual Basic toolbox. Some controls are useful for working with large amounts of data contained in an external database. Other controls can
be used to access the Windows file system. Still other controls defy categorization, but are useful nonetheless.
Understanding Properties, Methods and Events
Designing a Form You can also use ActiveX controls, previously called custom or OLE controls, in a Visual Basic application in the same way that you use the standard controls. The Professional and Enterprise
Clicking Buttons to Perform Actions editions of Visual Basic include several ActiveX controls as well as the capability to build your own controls. Additional ActiveX controls for just about any purpose imaginable are available for
purchase from numerous vendors.
Controls for Displaying and Entering Text
Controls That Present Choices to Users For More Information For additional information on using ActiveX controls, see "Managing Projects."
Controls That Display Pictures and Graphics
Additional Controls Data Access Controls
Understanding Focus
Setting the Tab Order In today's business, most information is stored in one or more central databases. Visual Basic includes several data access controls for accessing most popular databases, including Microsoft
Access and SQL Server.
Menu Basics
Prompting the User with Dialog Boxes ● The ADO Data control is used to connect to a database. Think of it as a pipeline between the database and the other controls on your form. Its properties, methods, and events allow you to navigate and manipulate external data from within your own
application.

● The DataList control is similar to the list box control. When used in conjunction with an ADO Data control, it can be automatically filled with a list of data from a field in an external database.

● The DataCombo control is like a combination of the DataList control and a text box. The selected text in the text box portion can be edited, with the changes appearing in the underlying database.

● The DataGrid control displays data in a grid or table. When used in conjunction with an ADO Data control, it presents fully editable data from multiple fields in an external database.

● The Microsoft Hierarchical FlexGrid control is a unique control for presenting multiple views of data. Think of it as a combination of a grid and a tree or outline control. At run time, the user can rearrange columns and rows to provide different views of the
data.

For More Information For additional information on data access controls, see "Using Visual Basic's Standard Controls." For more information on working with external data, see the Visual
Basic Data Access Guide.

File System Controls

Visual Basic includes three controls for adding file handling capabilities to your application. These controls are normally used together to provide a view of drives, directories and files; they
have special properties and events that tie them together.

● The DriveListBox control looks like a combo box. It provides a drop-down list of drives from which the user can select.

● The DirListBox is similar to a list box control, but with the built-in capability of displaying a list of directories in the currently selected drive.

● The FileListBox control also looks like a list box with a list of file names in a selected directory.

Note These controls are provided primarily for backward compatibility with applications created in earlier versions of Visual Basic. The common dialog control provides an easier method of
working with file access. For more information on common dialog control, see "Miscellaneous Controls" later in this chapter.

Miscellaneous Controls

Several other standard controls are included in Visual Basic. Each serves a unique purpose.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconadditionalcontrols.asp (1 of 2) [11/17/2002 10:36:27 PM]


Welcome to the MSDN Library

● The timer control can be used to create an event in your application at a recurring interval. This is useful for executing code without the need for user interaction.

● The OLE container control is an easy way to add capabilities like linking and embedding to your application. Through the OLE container control, you can provide access to the functionality of any OLE-enabled application such as Microsoft Excel, Word and
many others.

● The common dialog control adds built-in dialog boxes to your application for the selection of files, colors, fonts, and printing functions.

For More Information For additional information on any of the standard controls, see "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconadditionalcontrols.asp (2 of 2) [11/17/2002 10:36:27 PM]


Understanding Focus

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

Visual Basic Concepts

Understanding Focus

See Also

Focus is the ability to receive user input through the mouse or keyboard. When an object has the focus, it can receive input from a user. In the Microsoft Windows interface, several applications
can be running at any time, but only the application with the focus will have an active title bar and can receive user input. On a Visual Basic form with several text boxes, only the text box with the
focus will display text entered by means of the keyboard.

The GotFocus and LostFocus events occur when an object receives or loses focus. Forms and most controls support these events.

Event Description

GotFocus Occurs when an object receives focus.

LostFocus Occurs when an object loses focus. A LostFocus event procedure is primarily used for verification and validation updates, or for reversing or changing conditions you set up in the object's
GotFocus procedure.

You can give focus to an object by:

● Selecting the object at run time.

● Using an access key to select the object at run time.

● Using the SetFocus method in code.

You can see when some objects have the focus. For example, when command buttons have the focus, they appear with a highlighted border around the caption (see Figure 3.19).

Figure 3.19 A command button showing focus

An object can receive focus only if its Enabled and Visible properties are set to True. The Enabled property allows the object to respond to user-generated events such as keyboard and mouse
events. The Visible property determines whether an object is visible on the screen.

Note A form can receive focus only if it doesn't contain any controls that can receive the focus.

Validate Event of Controls

Controls also have a Validate event, which occurs before a control loses focus. However, this event occurs only when the CausesValidation property of the control that is about to receive the focus
is set to True. In many cases, because the Validate event occurs before the focus is lost, it is more appropriate than the LostFocus event for data validation. For more information, see "Validating
Control Data By Restricting Focus" in "Using Visual Basic's Standard

Controls That Can't Receive Focus

Some controls, such as the lightweight controls, cannot receive focus. Lightweight controls include the following:

● Frame control

● Image control

● Label control

● Line control

● Shape control

Additionally, controls that are invisible at run time, such as the Timer control, cannot receive focus.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconunderstandingfocus.asp?frame=true (1 of 2) [11/17/2002 10:37:46 PM]


Understanding Focus

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconunderstandingfocus.asp?frame=true (2 of 2) [11/17/2002 10:37:46 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

MSDN Library GO
Advanced Search Visual Basic Concepts

Understanding Focus

See Also

Up One Level Focus is the ability to receive user input through the mouse or keyboard. When an object has the focus, it can receive input from a user. In the Microsoft Windows interface, several
applications can be running at any time, but only the application with the focus will have an active title bar and can receive user input. On a Visual Basic form with several text boxes, only the
Understanding Properties, Methods and Events text box with the focus will display text entered by means of the keyboard.

Designing a Form
Clicking Buttons to Perform Actions The GotFocus and LostFocus events occur when an object receives or loses focus. Forms and most controls support these events.

Controls for Displaying and Entering Text


Controls That Present Choices to Users Event Description

Controls That Display Pictures and Graphics


GotFocus Occurs when an object receives focus.

Additional Controls
Understanding Focus
LostFocus Occurs when an object loses focus. A LostFocus event procedure is primarily used for verification and validation updates, or for reversing or changing conditions you set up in the object's
GotFocus procedure.

Setting the Tab Order


Menu Basics
You can give focus to an object by:
Prompting the User with Dialog Boxes
● Selecting the object at run time.

● Using an access key to select the object at run time.

● Using the SetFocus method in code.

You can see when some objects have the focus. For example, when command buttons have the focus, they appear with a highlighted border around the caption (see Figure 3.19).

Figure 3.19 A command button showing focus

An object can receive focus only if its Enabled and Visible properties are set to True. The Enabled property allows the object to respond to user-generated events such as keyboard and mouse
events. The Visible property determines whether an object is visible on the screen.

Note A form can receive focus only if it doesn't contain any controls that can receive the focus.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconunderstandingfocus.asp (1 of 2) [11/17/2002 10:37:49 PM]


Welcome to the MSDN Library

Validate Event of Controls

Controls also have a Validate event, which occurs before a control loses focus. However, this event occurs only when the CausesValidation property of the control that is about to receive the
focus is set to True. In many cases, because the Validate event occurs before the focus is lost, it is more appropriate than the LostFocus event for data validation. For more information, see
"Validating Control Data By Restricting Focus" in "Using Visual Basic's Standard

Controls That Can't Receive Focus

Some controls, such as the lightweight controls, cannot receive focus. Lightweight controls include the following:

● Frame control

● Image control

● Label control

● Line control

● Shape control

Additionally, controls that are invisible at run time, such as the Timer control, cannot receive focus.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconunderstandingfocus.asp (2 of 2) [11/17/2002 10:37:49 PM]


Setting the Tab Order

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

Visual Basic Concepts

Setting the Tab Order

See Also

The tab order is the order in which a user moves from one control to another by pressing the TAB key. Each form has its own tab order. Usually, the tab order is the same as the order in which
you created the controls.

For example, assume you create two text boxes, Text1 and Text2, and then a command button, Command1. When the application starts, Text1 has the focus. Pressing TAB moves the focus
between controls in the order they were created, as shown in Figure 3.20.

Figure 3.20 Tab example

To change the tab order for a control, set the TabIndex property. The TabIndex property of a control determines where it is positioned in the tab order. By default, the first control drawn has a
TabIndex value of 0, the second has a TabIndex of 1, and so on. When you change a control's tab order position, Visual Basic automatically renumbers the tab order positions of the other controls
to reflect insertions and deletions. For example, if you make Command1 first in the tab order, the TabIndex values for the other controls are automatically adjusted upward, as shown in the
following table.

TabIndex before it is changed TabIndex after it is changed


Control

Text1 0 1

Text2 1 2

Command1 2 0

The highest TabIndex setting is always one less than the number of controls in the tab order (because numbering starts at 0). Even if you set the TabIndex property to a number higher than the
number of controls, Visual Basic converts the value back to the number of controls minus 1.

Note Controls that cannot get the focus, as well as disabled and invisible controls, don't have a TabIndex property and are not included in the tab order. As a user presses the TAB key, these
controls are skipped.

Removing a Control from the Tab Order

Usually, pressing TAB at run time selects each control in the tab order. You can remove a control from the tab order by setting its TabStop property to False (0).

A control whose TabStop property has been set to False still maintains its position in the actual tab order, even though the control is skipped when you cycle through the controls with the TAB key.

Note An option button group has a single tab stop. The selected button (that is, the button with its Value set to True) has its TabStop property automatically set to True, while the other buttons
have their TabStop property set to False.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconsettingtaborder.asp?frame=true [11/17/2002 10:38:04 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

MSDN Library GO
Advanced Search Visual Basic Concepts

Setting the Tab Order

See Also

Up One Level The tab order is the order in which a user moves from one control to another by pressing the TAB key. Each form has its own tab order. Usually, the tab order is the same as the order in which
you created the controls.
Understanding Properties, Methods and Events
Designing a Form For example, assume you create two text boxes, Text1 and Text2, and then a command button, Command1. When the application starts, Text1 has the focus. Pressing TAB moves the focus
Clicking Buttons to Perform Actions between controls in the order they were created, as shown in Figure 3.20.

Controls for Displaying and Entering Text


Controls That Present Choices to Users Figure 3.20 Tab example

Controls That Display Pictures and Graphics


Additional Controls
Understanding Focus
Setting the Tab Order
Menu Basics
Prompting the User with Dialog Boxes

To change the tab order for a control, set the TabIndex property. The TabIndex property of a control determines where it is positioned in the tab order. By default, the first control drawn has a
TabIndex value of 0, the second has a TabIndex of 1, and so on. When you change a control's tab order position, Visual Basic automatically renumbers the tab order positions of the other
controls to reflect insertions and deletions. For example, if you make Command1 first in the tab order, the TabIndex values for the other controls are automatically adjusted upward, as shown
in the following table.

TabIndex before it is changed TabIndex after it is changed


Control

Text1 0 1

Text2 1 2

Command1 2 0

The highest TabIndex setting is always one less than the number of controls in the tab order (because numbering starts at 0). Even if you set the TabIndex property to a number higher than
the number of controls, Visual Basic converts the value back to the number of controls minus 1.

Note Controls that cannot get the focus, as well as disabled and invisible controls, don't have a TabIndex property and are not included in the tab order. As a user presses the TAB key, these

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconsettingtaborder.asp (1 of 2) [11/17/2002 10:38:06 PM]


Welcome to the MSDN Library
controls are skipped.

Removing a Control from the Tab Order

Usually, pressing TAB at run time selects each control in the tab order. You can remove a control from the tab order by setting its TabStop property to False (0).

A control whose TabStop property has been set to False still maintains its position in the actual tab order, even though the control is skipped when you cycle through the controls with the TAB
key.

Note An option button group has a single tab stop. The selected button (that is, the button with its Value set to True) has its TabStop property automatically set to True, while the other
buttons have their TabStop property set to False.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconsettingtaborder.asp (2 of 2) [11/17/2002 10:38:06 PM]


Menu Basics

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

Visual Basic Concepts

Menu Basics

See Also

If you want your application to provide a set of commands to users, menus offer a convenient and consistent way to group commands and an easy way for users to access them.

Figure 3.21 Illustrates the elements of a menu interface on an untitled form.

Figure 3.21 The elements of a menu interface on a Visual Basic form

The menu bar appears immediately below the title bar on the form and contains one or more menu titles. When you click a menu title (such as File), a menu containing a list of menu items drops
down. Menu items can include commands (such as New and Exit), separator bars, and submenu titles. Each menu item the user sees corresponds to a menu control you define in the Menu Editor
(described later in this chapter).

To make your application easier to use, you should group menu items according to their function. In Figure 3.21, for example, the file-related commands New, Open, and Save As… are all found
on the File menu.

Some menu items perform an action directly; for example, the Exit menu item on the File menu closes the application. Other menu items display a dialog box — a window that requires the user to
supply information needed by the application to perform the action. These menu items should be followed by an ellipsis (…). For example, when you choose Save As… from the File menu, the Save
File As dialog box appears.

A menu control is an object; like other objects it has properties that can be used to define its appearance and behavior. You can set the Caption property, the Enabled and Visible properties, the
Checked property, and others at design time or at run time. Menu controls contain only one event, the Click event, which is invoked when the menu control is selected with the mouse or using the
keyboard.

For More Information For additional information on menu controls, see "Creating Menus with the Menu Editor" in "Creating a User Interface."

Pop-up Menus

A pop-up menu is a floating menu that is displayed over a form, independent of the menu bar, as shown in Figure 3.22. The items displayed on the pop-up menu depend on the location of the
pointer when the right mouse button is pressed; therefore, pop-up menus are also called context menus. (In Windows 95 or later, you activate context menus by clicking the right mouse button.)
You should use pop-up menus to provide an efficient method for accessing common, contextual commands. For example, if you click a text box with the right mouse button, a contextual menu
would appear, as shown in Figure 3.22.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconmenubasics.asp?frame=true (1 of 3) [11/17/2002 10:38:15 PM]


Menu Basics

Figure 3.22 A pop-up menu

Any menu that has at least one menu item can be displayed at run time as a pop-up menu. To display a pop-up menu, use the PopupMenu method.

For More Information For additional information on creating pop-up menus, see "Creating Menus" in "Creating a User Interface."

Using the Menu Editor

With the Menu Editor, you can add new commands to existing menus, replace existing menu commands with your own commands, create new menus and menu bars, and change and delete
existing menus and menu bars. The main advantage of the Menu Editor is its ease of use. You can customize menus in a completely interactive manner that involves very little programming.

To display the Menu Editor

● From the Tools menu, choose Menu Editor.

This opens the Menu Editor, shown in Figure 3.23

Figure 3.23 The Menu Editor

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconmenubasics.asp?frame=true (2 of 3) [11/17/2002 10:38:15 PM]


Menu Basics

While most menu control properties can be set using the Menu Editor; all menu properties are also available in the Properties window. You would normally create a menu in the Menu Editor;
however, to quickly change a single property, you could use the Properties window.

For More Information For additional information on creating menus and using the Menu Editor, see "Creating Menus" in "Creating a User Interface."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconmenubasics.asp?frame=true (3 of 3) [11/17/2002 10:38:15 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

MSDN Library GO
Advanced Search Visual Basic Concepts

Menu Basics

See Also

Up One Level If you want your application to provide a set of commands to users, menus offer a convenient and consistent way to group commands and an easy way for users to access them.

Understanding Properties, Methods and Events


Designing a Form Figure 3.21 Illustrates the elements of a menu interface on an untitled form.

Clicking Buttons to Perform Actions


Controls for Displaying and Entering Text Figure 3.21 The elements of a menu interface on a Visual Basic form

Controls That Present Choices to Users


Controls That Display Pictures and Graphics
Additional Controls
Understanding Focus
Setting the Tab Order
Menu Basics
Prompting the User with Dialog Boxes

The menu bar appears immediately below the title bar on the form and contains one or more menu titles. When you click a menu title (such as File), a menu containing a list of menu items
drops down. Menu items can include commands (such as New and Exit), separator bars, and submenu titles. Each menu item the user sees corresponds to a menu control you define in the
Menu Editor (described later in this chapter).

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconmenubasics.asp (1 of 3) [11/17/2002 10:38:17 PM]


Welcome to the MSDN Library
To make your application easier to use, you should group menu items according to their function. In Figure 3.21, for example, the file-related commands New, Open, and Save As… are all
found on the File menu.

Some menu items perform an action directly; for example, the Exit menu item on the File menu closes the application. Other menu items display a dialog box — a window that requires the
user to supply information needed by the application to perform the action. These menu items should be followed by an ellipsis (…). For example, when you choose Save As… from the File
menu, the Save File As dialog box appears.

A menu control is an object; like other objects it has properties that can be used to define its appearance and behavior. You can set the Caption property, the Enabled and Visible properties,
the Checked property, and others at design time or at run time. Menu controls contain only one event, the Click event, which is invoked when the menu control is selected with the mouse or
using the keyboard.

For More Information For additional information on menu controls, see "Creating Menus with the Menu Editor" in "Creating a User Interface."

Pop-up Menus

A pop-up menu is a floating menu that is displayed over a form, independent of the menu bar, as shown in Figure 3.22. The items displayed on the pop-up menu depend on the location of the
pointer when the right mouse button is pressed; therefore, pop-up menus are also called context menus. (In Windows 95 or later, you activate context menus by clicking the right mouse
button.) You should use pop-up menus to provide an efficient method for accessing common, contextual commands. For example, if you click a text box with the right mouse button, a
contextual menu would appear, as shown in Figure 3.22.

Figure 3.22 A pop-up menu

Any menu that has at least one menu item can be displayed at run time as a pop-up menu. To display a pop-up menu, use the PopupMenu method.

For More Information For additional information on creating pop-up menus, see "Creating Menus" in "Creating a User Interface."

Using the Menu Editor

With the Menu Editor, you can add new commands to existing menus, replace existing menu commands with your own commands, create new menus and menu bars, and change and delete
existing menus and menu bars. The main advantage of the Menu Editor is its ease of use. You can customize menus in a completely interactive manner that involves very little programming.

To display the Menu Editor

● From the Tools menu, choose Menu Editor.

This opens the Menu Editor, shown in Figure 3.23

Figure 3.23 The Menu Editor

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconmenubasics.asp (2 of 3) [11/17/2002 10:38:17 PM]


Welcome to the MSDN Library

While most menu control properties can be set using the Menu Editor; all menu properties are also available in the Properties window. You would normally create a menu in the Menu Editor;
however, to quickly change a single property, you could use the Properties window.

For More Information For additional information on creating menus and using the Menu Editor, see "Creating Menus" in "Creating a User Interface."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconmenubasics.asp (3 of 3) [11/17/2002 10:38:17 PM]


Prompting the User with Dialog Boxes

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

Visual Basic Concepts

Prompting the User with Dialog Boxes

See Also

In Windows-based applications, dialog boxes are used to prompt the user for data needed by the application to continue or to display information to the user. Dialog boxes are a specialized type of
form object that can be created in one of three ways:

● Predefined dialog boxes can be created from code using the MsgBox or InputBox functions.

● Customized dialog boxes can be created using a standard form or by customizing an existing dialog box.

● Standard dialog boxes, such as Print and File Open, can be created using the common dialog control.

Figure 3.24 shows an example of a predefined dialog box created using the MsgBox function.

Figure 3.24 A predefined dialog box

This dialog is displayed when you invoke the MsgBox function in code. The code for displaying the dialog box shown in Figure 3.24 looks like this:

MsgBox "Error encountered while trying to open file," & vbCrLf & "please retry.", vbExclamation, "Text Editor"

You supply three pieces of information, or arguments, to the MsgBox function: the message text, a constant (numeric value) to determine the style of the dialog box, and a title. Styles are
available with various combinations of buttons and icons to make creating dialog boxes easy.

Because most dialog boxes require user interaction, they are usually displayed as modal dialog boxes. A modal dialog box must be closed (hidden or unloaded) before you can continue working
with the rest of the application. For example, a dialog box is modal if it requires you to click OK or Cancel before you can switch to another form or dialog box.

Modeless dialog boxes let you shift the focus between the dialog box and another form without having to close the dialog box. You can continue to work elsewhere in the current application while
the dialog box is displayed. Modeless dialog boxes are rare; you will usually display a dialog because a response is needed before the application can continue. From the Edit menu, the Find dialog
box in Visual Basic is an example of a modeless dialog box. Use modeless dialog boxes to display frequently used commands or information.

For More Information For additional information on creating dialog boxes, see "Creating a User Interface."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconpromptinguserwithdialogs.asp?frame=true [11/17/2002 10:38:28 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus

MSDN Library GO
Advanced Search Visual Basic Concepts

Prompting the User with Dialog Boxes

See Also

Up One Level In Windows-based applications, dialog boxes are used to prompt the user for data needed by the application to continue or to display information to the user. Dialog boxes are a specialized
type of form object that can be created in one of three ways:
Understanding Properties, Methods and Events
Designing a Form ● Predefined dialog boxes can be created from code using the MsgBox or InputBox functions.

Clicking Buttons to Perform Actions ● Customized dialog boxes can be created using a standard form or by customizing an existing dialog box.

Standard dialog boxes, such as Print and File Open, can be created using the common dialog control.
Controls for Displaying and Entering Text

Controls That Present Choices to Users Figure 3.24 shows an example of a predefined dialog box created using the MsgBox function.

Controls That Display Pictures and Graphics


Additional Controls Figure 3.24 A predefined dialog box

Understanding Focus
Setting the Tab Order
Menu Basics
Prompting the User with Dialog Boxes

This dialog is displayed when you invoke the MsgBox function in code. The code for displaying the dialog box shown in Figure 3.24 looks like this:

MsgBox "Error encountered while trying to open file," & vbCrLf & "please retry.", vbExclamation, "Text Editor"

You supply three pieces of information, or arguments, to the MsgBox function: the message text, a constant (numeric value) to determine the style of the dialog box, and a title. Styles are
available with various combinations of buttons and icons to make creating dialog boxes easy.

Because most dialog boxes require user interaction, they are usually displayed as modal dialog boxes. A modal dialog box must be closed (hidden or unloaded) before you can continue working
with the rest of the application. For example, a dialog box is modal if it requires you to click OK or Cancel before you can switch to another form or dialog box.

Modeless dialog boxes let you shift the focus between the dialog box and another form without having to close the dialog box. You can continue to work elsewhere in the current application
while the dialog box is displayed. Modeless dialog boxes are rare; you will usually display a dialog because a response is needed before the application can continue. From the Edit menu, the
Find dialog box in Visual Basic is an example of a modeless dialog box. Use modeless dialog boxes to display frequently used commands or information.

For More Information For additional information on creating dialog boxes, see "Creating a User Interface."

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconpromptinguserwithdialogs.asp (1 of 2) [11/17/2002 10:38:30 PM]


Welcome to the MSDN Library

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconpromptinguserwithdialogs.asp (2 of 2) [11/17/2002 10:38:30 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics

MSDN Library GO
Advanced Search Visual Basic Concepts

Managing Projects

See Also

Up One Level To create an application with Visual Basic, you work with projects. A project is the collection of files you use to build an application. This chapter describes how to build and manage projects.

Working with Projects


The Structure of a Visual Basic Project When you create an application, you will usually create new forms; you might also reuse or modify forms that were created for previous projects. The same is true for other modules or files
that you might include in your project. ActiveX controls and objects from other applications can also be shared between projects.
Creating, Opening, and Saving Projects
Adding, Removing, and Saving Files After all of the components in a project have been assembled and the code written, you compile your project to create an executable file.
Adding Controls to a Project
Making and Running an Executable File Topics

Setting Project Options


Using Wizards and Add-Ins Working with Projects

An introduction to projects, the Project Explorer, and project files.

The Structure of a Visual Basic Project

A discussion of the components that make up a project.

Creating, Opening, and Saving Projects

The basics of working with projects.

Adding, Removing, and Saving Files

The basics of working with the files within a project.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconmanagingprojects.asp (1 of 2) [11/17/2002 10:39:34 PM]


Welcome to the MSDN Library

Adding Controls to a Project

The basics of working with ActiveX controls and insertable objects.

Making and Running an Executable File

The basics of compiling a project.

Setting Project Options

A discussion of some of the options that can be set on a project by project basis.

Using Wizards and Add-Ins

A discussion of additional tools for working with projects and extending Visual Basic.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconmanagingprojects.asp (2 of 2) [11/17/2002 10:39:34 PM]


Working with Projects

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

Visual Basic Concepts

Working with Projects

See Also

As you develop an application, you work with a project to manage all the different files that make up the application. A project consists of:

● One project file that keeps track of all the components (.vbp).

● One file for each form (.frm).

● One binary data file for each form containing data for properties of controls on the form (.frx). These files are not editable and are automatically generated for any .frm file that contains binary properties, such as Picture or Icon.

● Optionally, one file for each class module (.cls).

● Optionally, one file for each standard module (.bas).

● Optionally, one or more files containing ActiveX controls (.ocx).

● Optionally, a single resource file (.res).

The project file is simply a list of all the files and objects associated with the project, as well as information on the environment options you set. This information is updated every time you save
the project. All of the files and objects can be shared by other projects as well.

When you have completed all the files for a project, you can convert the project into an executable file (.exe): From the File menu, choose the Make project.exe command.

Note With the Professional and Enterprise editions of Visual Basic, you can also create other types of executable files such as .ocx and .dll files. References in this chapter assume a standard .exe
project; for additional information related to other project types see the Component Tools Guide.

For More Information For more details about creating executables, see "Making and Running an Executable File," later in this chapter. For information about binary data files and project files,
see "Visual Basic Specifications, Limitations, and File Formats."

The Project Explorer

As you create, add, or remove editable files from a project, Visual Basic reflects your changes in the Project Explorer window, which contains a current list of the files in the project. The Project
Explorer window in Figure 4.1 shows some of the types of files you can include in a Visual Basic project.

Figure 4.1 The Project Explorer window

The Project File

Each time you save a project, Visual Basic updates the project file (.vbp). A project file contains the same list of files that appears in the Project Explorer window, as well as references to the
ActiveX controls and insertable objects that are used in the project.

You can open an existing project file by double-clicking its icon, by choosing the Open Project command from the File menu, or by dragging the file and dropping it on the Project Explorer window.

For More Information The specific format of information stored in the .vbp file is described in "Visual Basic Specifications, Limitations, and File Formats."

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconworkingwithprojects.asp?frame=true (1 of 2) [11/17/2002 10:39:46 PM]


Working with Projects

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconworkingwithprojects.asp?frame=true (2 of 2) [11/17/2002 10:39:46 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

MSDN Library GO
Advanced Search Visual Basic Concepts

Working with Projects

See Also

Up One Level As you develop an application, you work with a project to manage all the different files that make up the application. A project consists of:

Working with Projects


The Structure of a Visual Basic Project ●


One project file that keeps track of all the components (.vbp).

One file for each form (.frm).

Creating, Opening, and Saving Projects ● One binary data file for each form containing data for properties of controls on the form (.frx). These files are not editable and are automatically generated for any .frm file that contains binary properties, such as Picture or Icon.

Adding, Removing, and Saving Files ●


Optionally, one file for each class module (.cls).

Optionally, one file for each standard module (.bas).

Adding Controls to a Project ● Optionally, one or more files containing ActiveX controls (.ocx).

Making and Running an Executable File


● Optionally, a single resource file (.res).

Setting Project Options The project file is simply a list of all the files and objects associated with the project, as well as information on the environment options you set. This information is updated every time you save
Using Wizards and Add-Ins the project. All of the files and objects can be shared by other projects as well.

When you have completed all the files for a project, you can convert the project into an executable file (.exe): From the File menu, choose the Make project.exe command.

Note With the Professional and Enterprise editions of Visual Basic, you can also create other types of executable files such as .ocx and .dll files. References in this chapter assume a standard
.exe project; for additional information related to other project types see the Component Tools Guide.

For More Information For more details about creating executables, see "Making and Running an Executable File," later in this chapter. For information about binary data files and project
files, see "Visual Basic Specifications, Limitations, and File Formats."

The Project Explorer

As you create, add, or remove editable files from a project, Visual Basic reflects your changes in the Project Explorer window, which contains a current list of the files in the project. The Project
Explorer window in Figure 4.1 shows some of the types of files you can include in a Visual Basic project.

Figure 4.1 The Project Explorer window

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconworkingwithprojects.asp (1 of 2) [11/17/2002 10:39:48 PM]


Welcome to the MSDN Library

The Project File

Each time you save a project, Visual Basic updates the project file (.vbp). A project file contains the same list of files that appears in the Project Explorer window, as well as references to the
ActiveX controls and insertable objects that are used in the project.

You can open an existing project file by double-clicking its icon, by choosing the Open Project command from the File menu, or by dragging the file and dropping it on the Project Explorer
window.

For More Information The specific format of information stored in the .vbp file is described in "Visual Basic Specifications, Limitations, and File Formats."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconworkingwithprojects.asp (2 of 2) [11/17/2002 10:39:48 PM]


The Structure of a Visual Basic Project

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

Visual Basic Concepts

The Structure of a Visual Basic Project

See Also

The following sections describe the different types of files and objects that you can include in a project.

Form Modules

Form modules (.frm file name extension) can contain textual descriptions of the form and its controls, including their property settings. They can also contain form-level declarations of constants,
variables, and external procedures; event procedures; and general procedures.

For More Information For more about creating forms, see "Developing an Application in Visual Basic" and "Creating a User Interface." For information about the format and content of form
files, see "Visual Basic Specifications, Limitations, and File Formats."

Class Modules

Class modules (.cls file name extension) are similar to form modules, except that they have no visible user interface. You can use class modules to create your own objects, including code for
methods and properties.

For More Information For information about writing code in class modules, see "Creating Your Own Classes" in "Programming with Objects."

Standard Modules

Standard modules (.bas file name extension) can contain public or module-level declarations of types, constants, variables, external procedures, and public procedures.

For More Information For information about using modules, see "Programming Fundamentals" and "Programming with Objects."

Resource Files

Resource files (.res file name extension) contain bitmaps, text strings, and other data that you can change without having to re-edit your code. For example, if you plan to localize your application
in a foreign language, you can keep all of the user-interface text strings and bitmaps in a resource file, which you can then localize instead of the entire application. A project can contain no more
than one resource file.

For More Information For more information on using resource files, see "Using a Resource File" later in this chapter, and "International Issues."

ActiveX Documents

ActiveX documents (.dob) are similar to forms, but are displayable in an Internet browser such as Internet Explorer. The Professional and Enterprise editions of Visual Basic are capable of creating
ActiveX documents.

For More Information For more information on ActiveX documents, see "Creating ActiveX Components" in the Component Tools Guide.

User Control and Property Page Modules

User Control (.ctl) and Property Page (.pag) modules are also similar to forms, but are used to create ActiveX controls and their associated property pages for displaying design-time properties.
The Professional and Enterprise editions of Visual Basic are capable of creating ActiveX controls.

For More Information For more information on ActiveX control creation, see "Creating an ActiveX Control" in "Creating ActiveX Components," in the Component Tools Guide.

Components

In addition to files and modules, several other types of components can be added to the project.

ActiveX Controls

http://msdn.microsoft.com/library/en-us/vbcon98/ht...conthestructureofvisualbasicproject.asp?frame=true (1 of 2) [11/17/2002 10:39:53 PM]


The Structure of a Visual Basic Project

ActiveX controls (.ocx file name extension) are optional controls which can be added to the toolbox and used on forms. When you install Visual Basic, the files containing the controls included with
Visual Basic are copied to a common directory (the \Windows\System subdirectory under Windows 95 or later). Additional ActiveX controls are available from a wide variety of sources. You can
also create your own controls using the Professional or Enterprise editions of Visual Basic.

For More Information For more information on using the included ActiveX controls, see "Using the ActiveX Controls" in the Component Tools Guide.

Insertable Objects
Insertable objects, such as a Microsoft Excel Worksheet object, are components you can use as building blocks to build integrated solutions. An integrated solution can contain data in different
formats, such as spreadsheets, bitmaps, and text, which were all created by different applications.

For More Information For more information on using other applications' objects, see "Programming with Components."

References
You can also add references to external ActiveX components that may be used by your application. You assign references by using the References dialog, accessed from the References menu item
on the Project menu.

For More Information For more information on references, see "Using Other Applications' Objects" later in this chapter.

ActiveX Designers
ActiveX designers are tools for designing classes from which objects can be created. The design interface for forms is the default designer. Additional designers may be available from other
sources.

For More Information For more information about ActiveX designers, see "ActiveX Designers" in "Programming with Objects."

Standard Controls

Standard controls are supplied by Visual Basic. Standard controls, such as the command button or frame control, are always included in the toolbox, unlike ActiveX controls and insertable objects,
which can be removed from or added to the toolbox.

For More Information For more information on standard controls, see "Forms, Controls, and Menus" and "Using Visual Basic's Standard Controls."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/ht...conthestructureofvisualbasicproject.asp?frame=true (2 of 2) [11/17/2002 10:39:53 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

MSDN Library GO
Advanced Search Visual Basic Concepts

The Structure of a Visual Basic Project

See Also

Up One Level The following sections describe the different types of files and objects that you can include in a project.

Working with Projects


The Structure of a Visual Basic Project Form Modules

Creating, Opening, and Saving Projects


Form modules (.frm file name extension) can contain textual descriptions of the form and its controls, including their property settings. They can also contain form-level declarations of
Adding, Removing, and Saving Files constants, variables, and external procedures; event procedures; and general procedures.

Adding Controls to a Project


Making and Running an Executable File For More Information For more about creating forms, see "Developing an Application in Visual Basic" and "Creating a User Interface." For information about the format and content of form
files, see "Visual Basic Specifications, Limitations, and File Formats."
Setting Project Options
Using Wizards and Add-Ins
Class Modules

Class modules (.cls file name extension) are similar to form modules, except that they have no visible user interface. You can use class modules to create your own objects, including code for
methods and properties.

For More Information For information about writing code in class modules, see "Creating Your Own Classes" in "Programming with Objects."

Standard Modules

Standard modules (.bas file name extension) can contain public or module-level declarations of types, constants, variables, external procedures, and public procedures.

For More Information For information about using modules, see "Programming Fundamentals" and "Programming with Objects."

Resource Files

Resource files (.res file name extension) contain bitmaps, text strings, and other data that you can change without having to re-edit your code. For example, if you plan to localize your
application in a foreign language, you can keep all of the user-interface text strings and bitmaps in a resource file, which you can then localize instead of the entire application. A project can
contain no more than one resource file.

For More Information For more information on using resource files, see "Using a Resource File" later in this chapter, and "International Issues."

ActiveX Documents

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthestructureofvisualbasicproject.asp (1 of 3) [11/17/2002 10:39:55 PM]


Welcome to the MSDN Library
ActiveX documents (.dob) are similar to forms, but are displayable in an Internet browser such as Internet Explorer. The Professional and Enterprise editions of Visual Basic are capable of
creating ActiveX documents.

For More Information For more information on ActiveX documents, see "Creating ActiveX Components" in the Component Tools Guide.

User Control and Property Page Modules

User Control (.ctl) and Property Page (.pag) modules are also similar to forms, but are used to create ActiveX controls and their associated property pages for displaying design-time properties.
The Professional and Enterprise editions of Visual Basic are capable of creating ActiveX controls.

For More Information For more information on ActiveX control creation, see "Creating an ActiveX Control" in "Creating ActiveX Components," in the Component Tools Guide.

Components

In addition to files and modules, several other types of components can be added to the project.

ActiveX Controls
ActiveX controls (.ocx file name extension) are optional controls which can be added to the toolbox and used on forms. When you install Visual Basic, the files containing the controls included
with Visual Basic are copied to a common directory (the \Windows\System subdirectory under Windows 95 or later). Additional ActiveX controls are available from a wide variety of sources. You
can also create your own controls using the Professional or Enterprise editions of Visual Basic.

For More Information For more information on using the included ActiveX controls, see "Using the ActiveX Controls" in the Component Tools Guide.

Insertable Objects
Insertable objects, such as a Microsoft Excel Worksheet object, are components you can use as building blocks to build integrated solutions. An integrated solution can contain data in different
formats, such as spreadsheets, bitmaps, and text, which were all created by different applications.

For More Information For more information on using other applications' objects, see "Programming with Components."

References
You can also add references to external ActiveX components that may be used by your application. You assign references by using the References dialog, accessed from the References menu
item on the Project menu.

For More Information For more information on references, see "Using Other Applications' Objects" later in this chapter.

ActiveX Designers
ActiveX designers are tools for designing classes from which objects can be created. The design interface for forms is the default designer. Additional designers may be available from other
sources.

For More Information For more information about ActiveX designers, see "ActiveX Designers" in "Programming with Objects."

Standard Controls

Standard controls are supplied by Visual Basic. Standard controls, such as the command button or frame control, are always included in the toolbox, unlike ActiveX controls and insertable
objects, which can be removed from or added to the toolbox.

For More Information For more information on standard controls, see "Forms, Controls, and Menus" and "Using Visual Basic's Standard Controls."

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthestructureofvisualbasicproject.asp (2 of 3) [11/17/2002 10:39:55 PM]


Welcome to the MSDN Library

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthestructureofvisualbasicproject.asp (3 of 3) [11/17/2002 10:39:55 PM]


Creating, Opening, and Saving Projects

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

Visual Basic Concepts

Creating, Opening, and Saving Projects

See Also

Four commands on the File menu allow you to create, open, and save projects.

Menu command Description

New Project Closes the current project, prompting you to save any files that have changed. You can select a type of project from the New Project dialog. Visual Basic then creates a new project with a single
new file.

Open Project Closes the current project, prompting you to save any changes. Visual Basic then opens an existing project, including the forms, modules, and ActiveX controls listed in its project (.vbp) file.

Save Project Updates the project file of the current project and all of its form, standard, and class modules.

Save Project As Updates the project file of the current project, saving the project file under a file name that you specify. Visual Basic also prompts you to save any forms or modules that have changed.

It is also possible to share files between projects. A single file, such as a form, can be part of more than one project. Note that changes made to a form or module in one project will be propagated
amongst all projects that share that module.

For More Information For more information about sharing files, see "Adding, Removing, and Saving Files" later in this chapter.

Working with Multiple Projects

In the Professional and Enterprise editions of Visual Basic, it is possible to have more than one project open at a time. This is useful for building and testing solutions involving user-created
controls or other components. When more than one project is loaded, the caption of the Project Explorer window will change to Project Group and the components of all open projects will be
displayed.

To add an additional project to the current project group

1. From the File menu, choose Add Project.

The Add Project dialog box is displayed.

2. Select an existing project or a new project type, and choose Open.

To remove a project from the current project group

1. Select a project or a component of a project in the Project Explorer.

2. From the File menu, choose Remove Project.

For More Information To learn more about working with multiple projects, see "Creating ActiveX Components" in the Component Tools Guide.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconcreatingopeningsavingprojects.asp?frame=true [11/17/2002 10:40:02 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating, Opening, and Saving Projects

See Also

Up One Level Four commands on the File menu allow you to create, open, and save projects.

Working with Projects


The Structure of a Visual Basic Project Menu command Description

Creating, Opening, and Saving Projects


New Project Closes the current project, prompting you to save any files that have changed. You can select a type of project from the New Project dialog. Visual Basic then creates a new project with a

Adding, Removing, and Saving Files single new file.

Adding Controls to a Project Open Project Closes the current project, prompting you to save any changes. Visual Basic then opens an existing project, including the forms, modules, and ActiveX controls listed in its project (.vbp) file.

Making and Running an Executable File Save Project Updates the project file of the current project and all of its form, standard, and class modules.

Setting Project Options


Save Project As Updates the project file of the current project, saving the project file under a file name that you specify. Visual Basic also prompts you to save any forms or modules that have changed.

Using Wizards and Add-Ins

It is also possible to share files between projects. A single file, such as a form, can be part of more than one project. Note that changes made to a form or module in one project will be
propagated amongst all projects that share that module.

For More Information For more information about sharing files, see "Adding, Removing, and Saving Files" later in this chapter.

Working with Multiple Projects

In the Professional and Enterprise editions of Visual Basic, it is possible to have more than one project open at a time. This is useful for building and testing solutions involving user-created
controls or other components. When more than one project is loaded, the caption of the Project Explorer window will change to Project Group and the components of all open projects will be
displayed.

To add an additional project to the current project group

1. From the File menu, choose Add Project.

The Add Project dialog box is displayed.

2. Select an existing project or a new project type, and choose Open.

To remove a project from the current project group

1. Select a project or a component of a project in the Project Explorer.

2. From the File menu, choose Remove Project.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcreatingopeningsavingprojects.asp (1 of 2) [11/17/2002 10:40:04 PM]


Welcome to the MSDN Library
For More Information To learn more about working with multiple projects, see "Creating ActiveX Components" in the Component Tools Guide.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcreatingopeningsavingprojects.asp (2 of 2) [11/17/2002 10:40:04 PM]


Adding, Removing, and Saving Files

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

Visual Basic Concepts

Adding, Removing, and Saving Files

See Also

Working with files within a project is similar to working with the projects themselves.

To add a file to a project

1. Select Project, Add filetype (where filetype is the type of file).

The Add filetype dialog box (Figure 4.2) is displayed.

2. Select an existing file or a new file type, and choose Open.

Figure 4.2 The Add Form dialog box

When you add a file to a project, you are simply including a reference to the existing file in the project; you are not adding a copy of the file. Therefore, if you make changes to a file and save it,
your changes will affect any project that includes the file. To change a file without affecting other projects, select the file in the Project Explorer, choose Save filename As from the File menu, and
then save the file under a new file name.

Note You can drag and drop files from the Windows Explorer, File Manager, or Network Neighborhood into the Project window to add them to a project. You can also drag and drop .ocx files onto
the toolbox to add new controls.

To remove a file from a project

1. Select the file in the Project Explorer.

2. From the Project menu, choose Remove filename.

3. The file will be removed from the project but not from the disk.

If you remove a file from a project, Visual Basic updates this information in the project file when you save it. If you delete a file outside of Visual Basic, however, Visual Basic cannot update the
project file; therefore, when you open the project, Visual Basic displays an error message warning you that a file is missing.

To save an individual file without saving the project

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconaddingremovingsavingfiles.asp?frame=true (1 of 2) [11/17/2002 10:40:17 PM]


Adding, Removing, and Saving Files

1. Select the file in the Project Explorer.

2. From the File menu, choose Save filename .

Merging Text

You can also insert existing text from other files into one of your code modules. This is useful for adding a list of constants or for adding snippets of code that you might have saved in text files.

To insert a text file into your code

1. From the Project window, select the form or module into which you want to insert code.

2. Choose the View Code button, and move the cursor to the point in the Code Editor where you want to insert code.

3. From the Edit menu, choose Insert File.

4. Select the name of the text file you want to insert, and choose Open.

Note If you edit Visual Basic source files using a text or code editor other than Visual Basic, be careful not to change settings of the attribute VB_PredeclaredId. In particular, changing this
attribute may cause serious problems with the GlobalMultiUse and GlobalSingleUse classes.

In general, you should not edit attributes manually, as doing so may put the module into an internally inconsistent state.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconaddingremovingsavingfiles.asp?frame=true (2 of 2) [11/17/2002 10:40:17 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

MSDN Library GO
Advanced Search Visual Basic Concepts

Adding, Removing, and Saving Files

See Also

Up One Level Working with files within a project is similar to working with the projects themselves.

Working with Projects


The Structure of a Visual Basic Project To add a file to a project

Creating, Opening, and Saving Projects


Adding, Removing, and Saving Files 1. Select Project, Add filetype (where filetype is the type of file).

Adding Controls to a Project The Add filetype dialog box (Figure 4.2) is displayed.

Making and Running an Executable File 2. Select an existing file or a new file type, and choose Open.

Setting Project Options


Figure 4.2 The Add Form dialog box
Using Wizards and Add-Ins

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconaddingremovingsavingfiles.asp (1 of 3) [11/17/2002 10:40:19 PM]


Welcome to the MSDN Library

When you add a file to a project, you are simply including a reference to the existing file in the project; you are not adding a copy of the file. Therefore, if you make changes to a file and save
it, your changes will affect any project that includes the file. To change a file without affecting other projects, select the file in the Project Explorer, choose Save filename As from the File menu,
and then save the file under a new file name.

Note You can drag and drop files from the Windows Explorer, File Manager, or Network Neighborhood into the Project window to add them to a project. You can also drag and drop .ocx files
onto the toolbox to add new controls.

To remove a file from a project

1. Select the file in the Project Explorer.

2. From the Project menu, choose Remove filename.

3. The file will be removed from the project but not from the disk.

If you remove a file from a project, Visual Basic updates this information in the project file when you save it. If you delete a file outside of Visual Basic, however, Visual Basic cannot update the
project file; therefore, when you open the project, Visual Basic displays an error message warning you that a file is missing.

To save an individual file without saving the project

1. Select the file in the Project Explorer.

2. From the File menu, choose Save filename .

Merging Text

You can also insert existing text from other files into one of your code modules. This is useful for adding a list of constants or for adding snippets of code that you might have saved in text files.

To insert a text file into your code

1. From the Project window, select the form or module into which you want to insert code.

2. Choose the View Code button, and move the cursor to the point in the Code Editor where you want to insert code.

3. From the Edit menu, choose Insert File.

4. Select the name of the text file you want to insert, and choose Open.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconaddingremovingsavingfiles.asp (2 of 3) [11/17/2002 10:40:19 PM]


Welcome to the MSDN Library
Note If you edit Visual Basic source files using a text or code editor other than Visual Basic, be careful not to change settings of the attribute VB_PredeclaredId. In particular, changing this
attribute may cause serious problems with the GlobalMultiUse and GlobalSingleUse classes.

In general, you should not edit attributes manually, as doing so may put the module into an internally inconsistent state.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconaddingremovingsavingfiles.asp (3 of 3) [11/17/2002 10:40:19 PM]


Adding Controls to a Project

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

Visual Basic Concepts

Adding Controls to a Project

See Also

The set of controls available in the toolbox can be customized for each project. Any given control must be in the toolbox before you can add it to a form in the project. The basic set of standard
controls that always appear in the toolbox is described in "Forms, Controls, and Menus."

Adding ActiveX Controls to a Project

You can add ActiveX controls and insertable objects to your project by adding them to the toolbox.

To add a control to a project's toolbox

1. From the Project menu, choose Components.

The Components dialog box is displayed, as shown in Figure 4.3. The items listed in this dialog box include all registered ActiveX controls, insertable objects, and ActiveX designers.

2. To add a control (.ocx file name extension) or an insertable object to the toolbox, select the check box to the left of the control name.

To view controls with .ocx file name extensions, select the Controls tab. To view insertable objects, such as a Microsoft Excel Chart, select the Insertable Objects tab.

3. Choose OK to close the Components dialog box. All of the ActiveX controls that you selected will now appear in the toolbox.

Figure 4.3 The Components dialog box

To add ActiveX controls to the Components dialog box, choose the Browse button, and search other directories for files with a .ocx file name extension. When you add an ActiveX control to the list
of available controls, Visual Basic automatically selects the check box.

Note Each ActiveX control is accompanied by a file with an .oca extension. This file stores cached type library information and other data specific to the control. The .oca files are typically stored

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconaddingcontrolstoproject.asp?frame=true (1 of 3) [11/17/2002 10:40:27 PM]


Adding Controls to a Project

in the same directory as the ActiveX controls and are recreated as needed (file sizes and dates may change).

Removing Controls from a Project

To remove a control from a project

1. From the Project menu, choose Components.

The Components dialog box is displayed.

2. Clear the check box next to each control you want to remove.

The control icons will be removed from the toolbox.

Note You cannot remove any control from the toolbox if an instance of that control is used on any form in the project.

Using Other Applications' Objects

You can also use objects from other applications, such as those included in the Microsoft Excel object library, either as controls in the toolbox or as programmable objects in your code. To add
objects to the toolbox, see "Adding Controls to a Project" earlier in this chapter.

To make another application's objects available in your code, but not as controls, set a reference to that application's object library.

To add a reference to another application's object library

1. From the Project menu, choose References.

The References dialog box is displayed, as shown in Figure 4.4.

2. Select the check box next to each reference you want to add to your project.

To add references to applications not listed in the References dialog box, choose the Browse button, and then select the application.

3. Choose OK to add the selected references to your project.

Figure 4.4 The References dialog box

If you are not using any objects in a referenced library, you should clear the check box for that reference to minimize the number of object references Visual Basic must resolve, thus reducing the
time it takes your project to compile.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconaddingcontrolstoproject.asp?frame=true (2 of 3) [11/17/2002 10:40:27 PM]


Adding Controls to a Project

Once you have set references to the object libraries you want, you can find a specific object and its methods and properties in the Object Browser by choosing Object Browser from the View menu.
You can use any object listed in the Object Browser in your code.

For More Information " For information on the Object Browser, see "Finding Out About Objects" in "Programming with Objects."

Using a Resource File

A resource file allows you to collect all of the version-specific text and bitmaps for an application in one place. This can include constant declarations, icons, screen text, and other material that
may change between localized versions or between revisions or specific configurations.

To add a file to a project

1. From the Project menu, select Add File.

The Add File dialog box is displayed.

2. Select an existing resource file (.res) and choose Open.

A single project can have only one resource file; if you add a second file with a .res extension, an error occurs.

For More Information For more information on the contents of a resource file, see "International Issues."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconaddingcontrolstoproject.asp?frame=true (3 of 3) [11/17/2002 10:40:27 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

MSDN Library GO
Advanced Search Visual Basic Concepts

Adding Controls to a Project

See Also

Up One Level The set of controls available in the toolbox can be customized for each project. Any given control must be in the toolbox before you can add it to a form in the project. The basic set of standard
controls that always appear in the toolbox is described in "Forms, Controls, and Menus."
Working with Projects
The Structure of a Visual Basic Project Adding ActiveX Controls to a Project
Creating, Opening, and Saving Projects
Adding, Removing, and Saving Files You can add ActiveX controls and insertable objects to your project by adding them to the toolbox.

Adding Controls to a Project


Making and Running an Executable File To add a control to a project's toolbox

Setting Project Options


Using Wizards and Add-Ins 1. From the Project menu, choose Components.

The Components dialog box is displayed, as shown in Figure 4.3. The items listed in this dialog box include all registered ActiveX controls, insertable objects, and ActiveX designers.

2. To add a control (.ocx file name extension) or an insertable object to the toolbox, select the check box to the left of the control name.

To view controls with .ocx file name extensions, select the Controls tab. To view insertable objects, such as a Microsoft Excel Chart, select the Insertable Objects tab.

3. Choose OK to close the Components dialog box. All of the ActiveX controls that you selected will now appear in the toolbox.

Figure 4.3 The Components dialog box

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconaddingcontrolstoproject.asp (1 of 4) [11/17/2002 10:40:29 PM]


Welcome to the MSDN Library

To add ActiveX controls to the Components dialog box, choose the Browse button, and search other directories for files with a .ocx file name extension. When you add an ActiveX control to the
list of available controls, Visual Basic automatically selects the check box.

Note Each ActiveX control is accompanied by a file with an .oca extension. This file stores cached type library information and other data specific to the control. The .oca files are typically
stored in the same directory as the ActiveX controls and are recreated as needed (file sizes and dates may change).

Removing Controls from a Project

To remove a control from a project

1. From the Project menu, choose Components.

The Components dialog box is displayed.

2. Clear the check box next to each control you want to remove.

The control icons will be removed from the toolbox.

Note You cannot remove any control from the toolbox if an instance of that control is used on any form in the project.

Using Other Applications' Objects

You can also use objects from other applications, such as those included in the Microsoft Excel object library, either as controls in the toolbox or as programmable objects in your code. To add
objects to the toolbox, see "Adding Controls to a Project" earlier in this chapter.

To make another application's objects available in your code, but not as controls, set a reference to that application's object library.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconaddingcontrolstoproject.asp (2 of 4) [11/17/2002 10:40:29 PM]


Welcome to the MSDN Library

To add a reference to another application's object library

1. From the Project menu, choose References.

The References dialog box is displayed, as shown in Figure 4.4.

2. Select the check box next to each reference you want to add to your project.

To add references to applications not listed in the References dialog box, choose the Browse button, and then select the application.

3. Choose OK to add the selected references to your project.

Figure 4.4 The References dialog box

If you are not using any objects in a referenced library, you should clear the check box for that reference to minimize the number of object references Visual Basic must resolve, thus reducing
the time it takes your project to compile.

Once you have set references to the object libraries you want, you can find a specific object and its methods and properties in the Object Browser by choosing Object Browser from the View
menu. You can use any object listed in the Object Browser in your code.

For More Information " For information on the Object Browser, see "Finding Out About Objects" in "Programming with Objects."

Using a Resource File

A resource file allows you to collect all of the version-specific text and bitmaps for an application in one place. This can include constant declarations, icons, screen text, and other material that
may change between localized versions or between revisions or specific configurations.

To add a file to a project

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconaddingcontrolstoproject.asp (3 of 4) [11/17/2002 10:40:29 PM]


Welcome to the MSDN Library
1. From the Project menu, select Add File.

The Add File dialog box is displayed.

2. Select an existing resource file (.res) and choose Open.

A single project can have only one resource file; if you add a second file with a .res extension, an error occurs.

For More Information For more information on the contents of a resource file, see "International Issues."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconaddingcontrolstoproject.asp (4 of 4) [11/17/2002 10:40:29 PM]


Making and Running an Executable File

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

Visual Basic Concepts

Making and Running an Executable File

See Also

You can make an executable file (.exe) from Visual Basic using the following procedure.

To make an executable file in Visual Basic

1. From the File menu, choose Make projectname .exe where projectname is the application name for the project.

2. Type a file name, or browse through the directories and select an existing file name to overwrite an existing executable with a newer version.

3. By clicking the Options button, you can also specify a number of version-specific details about the executable file in the Project Properties dialog box.

4. If you want to modify the version number of the project, set the appropriate Major, Minor, and Revision numbers. Selecting Auto Increment will automatically step the Revision number each time you run the Make projectname .exe command for this project.

5. To specify a new name for the application, under Application, type a new name in the Title box. If you want to specify a new icon, choose one from the list.

6. You can also enter version-specific commentary on a variety of issues under the Version Information box (comments, company name, trademark and copyright information, and so on) by selecting a topic from the list box and entering information in the text
box.

7. Choose OK to close the Project Properties dialog box, and then choose OK in the Make appname .exe dialog box to compile and link the executable file.

You can run the executable file like any other Windows-based application: double-click the icon for the executable file.

Note Building an executable file from the command line in a DOS session can be useful when you want to compile a project programmatically. In a batch file, type:

Vb6 /make projectname[.vbp] [exename]

For projectname, type the name of the project file. Use the variable exename to rename the resulting executable file.

Conditional Compilation

Conditional compilation lets you selectively compile certain parts of the program. You can include specific features of your program in different versions, such as changing the date and currency
display filters for an application distributed in several different languages.

For More Information To learn more about conditional compilation, see "Using Conditional Compilation" in "More About Programming."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconmakingrunningexecutablefile.asp?frame=true [11/17/2002 10:40:36 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

MSDN Library GO
Advanced Search Visual Basic Concepts

Making and Running an Executable File

See Also

Up One Level You can make an executable file (.exe) from Visual Basic using the following procedure.

Working with Projects


The Structure of a Visual Basic Project To make an executable file in Visual Basic

Creating, Opening, and Saving Projects


Adding, Removing, and Saving Files 1. From the File menu, choose Make projectname .exe where projectname is the application name for the project.

2. Type a file name, or browse through the directories and select an existing file name to overwrite an existing executable with a newer version.

Adding Controls to a Project 3. By clicking the Options button, you can also specify a number of version-specific details about the executable file in the Project Properties dialog box.

Making and Running an Executable File


4. If you want to modify the version number of the project, set the appropriate Major, Minor, and Revision numbers. Selecting Auto Increment will automatically step the Revision number each time you run the Make projectname .exe command for this
project.

Setting Project Options


5. To specify a new name for the application, under Application, type a new name in the Title box. If you want to specify a new icon, choose one from the list.

6. You can also enter version-specific commentary on a variety of issues under the Version Information box (comments, company name, trademark and copyright information, and so on) by selecting a topic from the list box and entering information in the

Using Wizards and Add-Ins


text box.

7. Choose OK to close the Project Properties dialog box, and then choose OK in the Make appname .exe dialog box to compile and link the executable file.

You can run the executable file like any other Windows-based application: double-click the icon for the executable file.

Note Building an executable file from the command line in a DOS session can be useful when you want to compile a project programmatically. In a batch file, type:

Vb6 /make projectname[.vbp] [exename]

For projectname, type the name of the project file. Use the variable exename to rename the resulting executable file.

Conditional Compilation

Conditional compilation lets you selectively compile certain parts of the program. You can include specific features of your program in different versions, such as changing the date and currency
display filters for an application distributed in several different languages.

For More Information To learn more about conditional compilation, see "Using Conditional Compilation" in "More About Programming."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconmakingrunningexecutablefile.asp (1 of 2) [11/17/2002 10:40:38 PM]


Welcome to the MSDN Library
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconmakingrunningexecutablefile.asp (2 of 2) [11/17/2002 10:40:38 PM]


Setting Project Options

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

Visual Basic Concepts

Setting Project Options

See Also

Visual Basic allows you to customize each project by setting a number of properties. Use the Project Properties dialog box, accessible through the Project Properties command on the Project menu.
Property settings are saved to the project (.vbp) file.

The following table describes some of the options you can set.

Option Description

Startup Object The first form that Visual Basic displays at run time, or Sub Main ( ).

Project Name Identifies the project in code. It can't contain periods (.), spaces, or start with a nonalphabetic character. For a public class name, the project name and class name cannot
exceed a total of 37 characters.

Help File The name of the Help file associated with the project.

Project Help Context ID The context ID for the specific Help topic to be called when the user selects the "?" button while the application's object library is selected in the Object Browser.

Project Description A user-friendly name for the project. Displayed in the References and Object Browser dialog boxes.

Many other options are also available, including those for compiling, components, and multithreading. When you're ready to access some of the more advanced options, you can find more
information by searching Help.

For More Information To learn about setting environment options that affect all projects, see "Developing An Application in Visual Basic."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconprojectoptions.asp?frame=true [11/17/2002 10:40:49 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

MSDN Library GO
Advanced Search Visual Basic Concepts

Setting Project Options

See Also

Up One Level Visual Basic allows you to customize each project by setting a number of properties. Use the Project Properties dialog box, accessible through the Project Properties command on the Project
menu. Property settings are saved to the project (.vbp) file.
Working with Projects
The Structure of a Visual Basic Project The following table describes some of the options you can set.
Creating, Opening, and Saving Projects
Adding, Removing, and Saving Files
Adding Controls to a Project Option Description

Making and Running an Executable File Startup Object The first form that Visual Basic displays at run time, or Sub Main ( ).

Setting Project Options Project Name Identifies the project in code. It can't contain periods (.), spaces, or start with a nonalphabetic character. For a public class name, the project name and class name cannot
exceed a total of 37 characters.
Using Wizards and Add-Ins
Help File The name of the Help file associated with the project.

Project Help Context ID The context ID for the specific Help topic to be called when the user selects the "?" button while the application's object library is selected in the Object Browser.

Project Description A user-friendly name for the project. Displayed in the References and Object Browser dialog boxes.

Many other options are also available, including those for compiling, components, and multithreading. When you're ready to access some of the more advanced options, you can find more
information by searching Help.

For More Information To learn about setting environment options that affect all projects, see "Developing An Application in Visual Basic."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconprojectoptions.asp [11/17/2002 10:40:51 PM]


Using Wizards and Add-Ins

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

Visual Basic Concepts

Using Wizards and Add-Ins

See Also

Visual Basic allows you to select and manage add-ins, which are extensions to Visual Basic. These extensions add capabilities to the Visual Basic development environment, for example, special
source code control capabilities.

Microsoft and other developers have created add-ins you can use in your applications. Wizards are a type of add-in that can simplify certain tasks, such as creating a form. Several wizards are
included in Visual Basic.

To have an add-in appear on the Add-In Manager dialog box, the developer of the add-in must ensure that it is installed properly.

Using the Add-In Manager

You can add or remove an add-in to your project by using the Add-In Manager, which is accessible from the Add-Ins menu. The Add-In Manager dialog box lists the available add-ins.

To install an add-in

1. From the Add-Ins menu, choose Add-In Manager.

2. Highlight an add-in from the list and click the desired behaviors in Load Behavior. To unload an add-in or prevent it from loading, clear all Load Behavior boxes.

3. When you are finished making your selections, choose OK.

Depending upon your Load Behavior selections, Visual Basic connects the selected add-ins and disconnects the cleared add-ins.

Visual Basic saves your add-in selections between editing sessions.

Note Selecting an add-in may add menu items to the Visual Basic Add-Ins menu.

Using Wizards

Wizards make working with Visual Basic even easier by providing task-specific assistance. For example, the Application Wizard included in Visual Basic helps you to create the framework for an
application by presenting a series of questions or choices. It generates the forms and the code behind the forms based on your choices; all you need to do is add code for your own specific
functionality.

The Professional and Enterprise editions of Visual Basic include other wizards, including a Data Form Wizard for creating forms to be used with databases, and an ActiveX Document Wizard for
converting forms for use in Internet applications.

Wizards are installed or removed using the Add-in Manager. Once installed, they will appear as selections on the Add-Ins menu. Some of the wizards also appear as icons in the related dialog
boxes; for example, the Application Wizard can also be accessed using its icon in the New Project dialog box.

To start the Application Wizard

● From the Add-Ins menu, choose Application Wizard.

–or–

1. From the File menu, choose New Project.

2. Select the Application Wizard icon.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconusingwizardsaddins.asp?frame=true [11/17/2002 10:40:56 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects

MSDN Library GO
Advanced Search Visual Basic Concepts

Using Wizards and Add-Ins

See Also

Up One Level Visual Basic allows you to select and manage add-ins, which are extensions to Visual Basic. These extensions add capabilities to the Visual Basic development environment, for example, special
source code control capabilities.
Working with Projects
The Structure of a Visual Basic Project Microsoft and other developers have created add-ins you can use in your applications. Wizards are a type of add-in that can simplify certain tasks, such as creating a form. Several wizards are
Creating, Opening, and Saving Projects included in Visual Basic.

Adding, Removing, and Saving Files


Adding Controls to a Project To have an add-in appear on the Add-In Manager dialog box, the developer of the add-in must ensure that it is installed properly.

Making and Running an Executable File


Setting Project Options Using the Add-In Manager

Using Wizards and Add-Ins


You can add or remove an add-in to your project by using the Add-In Manager, which is accessible from the Add-Ins menu. The Add-In Manager dialog box lists the available add-ins.

To install an add-in

1. From the Add-Ins menu, choose Add-In Manager.

2. Highlight an add-in from the list and click the desired behaviors in Load Behavior. To unload an add-in or prevent it from loading, clear all Load Behavior boxes.

3. When you are finished making your selections, choose OK.

Depending upon your Load Behavior selections, Visual Basic connects the selected add-ins and disconnects the cleared add-ins.

Visual Basic saves your add-in selections between editing sessions.

Note Selecting an add-in may add menu items to the Visual Basic Add-Ins menu.

Using Wizards

Wizards make working with Visual Basic even easier by providing task-specific assistance. For example, the Application Wizard included in Visual Basic helps you to create the framework for an
application by presenting a series of questions or choices. It generates the forms and the code behind the forms based on your choices; all you need to do is add code for your own specific
functionality.

The Professional and Enterprise editions of Visual Basic include other wizards, including a Data Form Wizard for creating forms to be used with databases, and an ActiveX Document Wizard for
converting forms for use in Internet applications.

Wizards are installed or removed using the Add-in Manager. Once installed, they will appear as selections on the Add-Ins menu. Some of the wizards also appear as icons in the related dialog

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusingwizardsaddins.asp (1 of 2) [11/17/2002 10:40:58 PM]


Welcome to the MSDN Library
boxes; for example, the Application Wizard can also be accessed using its icon in the New Project dialog box.

To start the Application Wizard

● From the Add-Ins menu, choose Application Wizard.

–or–

1. From the File menu, choose New Project.

2. Select the Application Wizard icon.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusingwizardsaddins.asp (2 of 2) [11/17/2002 10:40:58 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics

MSDN Library GO
Advanced Search Visual Basic Concepts

Programming Fundamentals

See Also

Up One Level This chapter introduces the essential components of the Visual Basic language. After creating the interface for your application using forms and controls, you will need to write the code that
defines the application's behavior. As with any modern programming language, Visual Basic supports a number of common programming constructs and language elements.
The Structure of a Visual Basic Application
Before You Start Coding Visual Basic is an object-based programming language. The mere mention of objects may cause undue anxiety in many programmers. Don't worry: whether you realize it or not, you've been
Code Writing Mechanics dealing with objects most of your life. Once you understand a few basic concepts, objects actually help to make programming easier than ever before.

Introduction to Variables, Constants and Data Types


Introduction to Procedures If you've programmed in other languages, much of the material covered in this chapter will seem familiar. While most of the constructs are similar to other languages, the event-driven nature
of Visual Basic introduces some subtle differences. Try and approach this material with an open mind; once you understand the differences you can use them to your advantage.
Introduction to Control Structures
Working with Objects If you're new to programming, the material in this chapter will serve as an introduction to the basic building blocks for writing code. Once you understand the basics, you will be able to create
powerful applications using Visual Basic.

Topics

The Structure of a Visual Basic Application

An introduction to the various components or modules that make up a Visual Basic application.

Before You Start Coding

A brief discussion of some of the considerations in designing an application.

Code Writing Mechanics

An introduction to the features of the Code Editor, plus the rules and regulations for writing code.

Introduction to Variables, Constants and Data Types

An introduction to the basic elements of the Visual Basic language.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconprogrammingfundamentals.asp (1 of 2) [11/17/2002 10:41:07 PM]


Welcome to the MSDN Library

Introduction to Procedures

An introduction to Sub and Function procedures.

Introduction to Control Structures

An introduction to decision structures and loops.

Working with Objects

An introduction to using objects in Visual Basic code.

Sample application

Vcr.vbp

Many of the code samples in this chapter are taken from the Vcr.vbp sample application which is listed in the Samples directory.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconprogrammingfundamentals.asp (2 of 2) [11/17/2002 10:41:07 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals

MSDN Library GO
Advanced Search Visual Basic Concepts

The Structure of a Visual Basic Application

See Also

Up One Level An application is really nothing more than a set of instructions directing the computer to perform a task or tasks. The structure of an application is the way in which the instructions are
organized; that is, where the instructions are stored and the order in which instructions are executed.
How an Event-Driven Application Works
Simple applications such as the classic "hello world" example have a simple structure; organization isn't very important with a single line of code. As applications become more complex, the
need for organization or structure becomes obvious. Imagine the chaos that would result if your application's code was allowed to execute in random order. In addition to controlling the
execution of an application, the structure is important to the programmer: how easily can you find specific instructions within your application?

Because a Visual Basic application is based on objects, the structure of its code closely models its physical representation on screen. By definition, objects contain data and code. The form that
you see on screen is a representation of the properties that define its appearance and intrinsic behavior. For each form in an application, there is a related form module (with file name
extension .frm) that contains its code.

Figure 5.1 A form and its related form module

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthestructureofvisualbasicapplication.asp (1 of 2) [11/17/2002 10:41:12 PM]


Welcome to the MSDN Library

Each form module contains event procedures — sections of code where you place the instructions that will execute in response to specific events. Forms can contain controls. For each control
on a form, there is a corresponding set of event procedures in the form module. In addition to event procedures, form modules can contain general procedures that are executed in response to
a call from any event procedure.

Code that isn't related to a specific form or control can be placed in a different type of module, a standard module (.BAS). A procedure that might be used in response to events in several
different objects should be placed in a standard module, rather than duplicating the code in the event procedures for each object.

A class module (.CLS) is used to create objects that can be called from procedures within your application. Whereas a standard module contains only code, a class module contains both code
and data — you can think of it as a control without a physical representation.

While "Managing Projects" describes which components you can add to an application, this chapter explains how to write code in the various components that make up an application. By
default, your project contains a single form module. You can add additional form, class, and standard modules, as needed. Class modules are discussed in "Programming with Objects."

● How an Event-Driven Application Works A discussion of the Event-driven model.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthestructureofvisualbasicapplication.asp (2 of 2) [11/17/2002 10:41:12 PM]


How an Event-Driven Application Works

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > The Structure of a Visual Basic Application

Visual Basic Concepts

How an Event-Driven Application Works

See Also

An event is an action recognized by a form or control. Event-driven applications execute Basic code in response to an event. Each form and control in Visual Basic has a predefined set of events. If
one of these events occurs and there is code in the associated event procedure, Visual Basic invokes that code.

Although objects in Visual Basic automatically recognize a predefined set of events, it is up to you to decide if and how they will respond to a particular event. A section of code — an event
procedure — corresponds to each event. When you want a control to respond to an event, you write code in the event procedure for that event.

The types of events recognized by an object vary, but many types are common to most controls. For example, most objects recognize a Click event — if a user clicks a form, code in the form's
Click event procedure is executed; if a user clicks a command button, code in the button's Click event procedure is executed. The actual code in each case will most likely be quite different.

Here's a typical sequence of events in an event-driven application:

1. The application starts and a form is loaded and displayed.

2. The form (or a control on the form) receives an event. The event might be caused by the user (for example, a keystroke), by the system (for example, a timer event), or indirectly by your code (for example, a Load event when your code loads a form).

3. If there is code in the corresponding event procedure, it executes.

4. The application waits for the next event.

Note Many events occur in conjunction with other events. For example, when the DblClick event occurs, the MouseDown, MouseUp, and Click events also occur.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconhoweventdrivenapplicationworks.asp?frame=true [11/17/2002 10:41:21 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > The Structure of a Visual Basic Application

MSDN Library GO
Advanced Search Visual Basic Concepts

How an Event-Driven Application Works

See Also

Up One Level An event is an action recognized by a form or control. Event-driven applications execute Basic code in response to an event. Each form and control in Visual Basic has a predefined set of
events. If one of these events occurs and there is code in the associated event procedure, Visual Basic invokes that code.
How an Event-Driven Application Works
Although objects in Visual Basic automatically recognize a predefined set of events, it is up to you to decide if and how they will respond to a particular event. A section of code — an event
procedure — corresponds to each event. When you want a control to respond to an event, you write code in the event procedure for that event.

The types of events recognized by an object vary, but many types are common to most controls. For example, most objects recognize a Click event — if a user clicks a form, code in the form's
Click event procedure is executed; if a user clicks a command button, code in the button's Click event procedure is executed. The actual code in each case will most likely be quite different.

Here's a typical sequence of events in an event-driven application:

1. The application starts and a form is loaded and displayed.

2. The form (or a control on the form) receives an event. The event might be caused by the user (for example, a keystroke), by the system (for example, a timer event), or indirectly by your code (for example, a Load event when your code loads a form).

3. If there is code in the corresponding event procedure, it executes.

4. The application waits for the next event.

Note Many events occur in conjunction with other events. For example, when the DblClick event occurs, the MouseDown, MouseUp, and Click events also occur.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconhoweventdrivenapplicationworks.asp [11/17/2002 10:41:22 PM]


Before You Start Coding

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals

Visual Basic Concepts

Before You Start Coding

See Also

Perhaps the most important (and often overlooked) part of creating an application in Visual Basic is the design phase. While it's obvious that you need to design a user interface for your
application, it may not be as obvious that you need to design the structure of the code. The way you structure your application can make a difference in its performance as well as in the
maintainability and usability of your code.

The code in a Visual Basic application is organized in a hierarchical fashion. A typical application consists of one or more modules: a form module for each form in the application, optional standard
modules for shared code, and optional class modules. Each module contains one or more procedures that contain the code: event procedures, Sub or Function procedures, and Property
procedures.

Determining which procedures belong in which module depends somewhat on the type of application that you are creating. Because Visual Basic is based on objects, it helps to think of your
application in terms of the objects that it represents. The design of the sample application for this chapter, Vcr.vbp, is based on the objects that comprise a video cassette recorder and a
television. The VCR application consists of two form modules, a standard module, and two class modules. You can use the Object Browser to examine the structure of the project (Figure 5.2).

Figure 5.2 The structure of the VCR project is shown in the Object Browser

The main form for the VCR application (frmVCR) is a visual representation of a combination VCR and television screen (Figure 5.3). It is composed of several objects that model those found in the
real world version. A group of Command buttons (cmdPlay, cmdRecord, and so on) mimic the buttons used to operate a VCR. The software VCR also contains a clock (lblTime), a channel indicator
(lblChannel), function indicators (shpPlay, shpRecord, and so on), and a "picture tube" (picTV). The event procedures for all of these objects are contained in the Vcr.frm form module.

Figure 5.3 The main form for the VCR application

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconbeforeyoustartcoding.asp?frame=true (1 of 2) [11/17/2002 10:41:29 PM]


Before You Start Coding

In many cases there are repetitive procedures that are shared by more than one object. For example, when the Play, Rewind, or Record buttons are "pushed," the Pause and Stop buttons need to
be enabled. Rather than repeat this code in each button's Click event procedure, it's better to create a shared Sub procedure that can be called by any button. If these procedures need to be
modified in the future, all of the modifications can be done in one place. This and other shared procedures are contained in the standard module, Vcr.bas.

Some parts of a VCR aren't visible, such as the tape transport mechanism or the logic for recording a television program. Likewise, some of the functions of the software VCR have no visual
representation. These are implemented as two class modules: Recorder.cls and Tape.cls. Code to initiate the "recording" process is contained in the clsRecorder module; code to control the
direction and speed of the "tape" is contained in the clsTape module. The classes defined in these modules have no direct references to any of the objects in the forms. Because they are
independent code modules, they could easily be reused to build an audio recorder without any modifications.

In addition to designing the structure of your code, it's important to establish naming conventions. By default, Visual Basic names the first form in a project Form1, the second Form2, and so on. If
you have several forms in an application, it's a good idea to give them meaningful names to avoid confusion when writing or editing your code. Some suggested naming conventions are presented
in "Visual Basic Coding Conventions."

As you learn more about objects and writing code, you can refer to the VCR sample application for examples of various different coding techniques.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconbeforeyoustartcoding.asp?frame=true (2 of 2) [11/17/2002 10:41:29 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals

MSDN Library GO
Advanced Search Visual Basic Concepts

Before You Start Coding

See Also

Up One Level Perhaps the most important (and often overlooked) part of creating an application in Visual Basic is the design phase. While it's obvious that you need to design a user interface for your
application, it may not be as obvious that you need to design the structure of the code. The way you structure your application can make a difference in its performance as well as in the
The Structure of a Visual Basic Application maintainability and usability of your code.

Before You Start Coding


Code Writing Mechanics The code in a Visual Basic application is organized in a hierarchical fashion. A typical application consists of one or more modules: a form module for each form in the application, optional
standard modules for shared code, and optional class modules. Each module contains one or more procedures that contain the code: event procedures, Sub or Function procedures, and
Introduction to Variables, Constants and Data Types Property procedures.

Introduction to Procedures
Introduction to Control Structures Determining which procedures belong in which module depends somewhat on the type of application that you are creating. Because Visual Basic is based on objects, it helps to think of your
application in terms of the objects that it represents. The design of the sample application for this chapter, Vcr.vbp, is based on the objects that comprise a video cassette recorder and a
Working with Objects television. The VCR application consists of two form modules, a standard module, and two class modules. You can use the Object Browser to examine the structure of the project (Figure 5.2).

Figure 5.2 The structure of the VCR project is shown in the Object Browser

The main form for the VCR application (frmVCR) is a visual representation of a combination VCR and television screen (Figure 5.3). It is composed of several objects that model those found in
the real world version. A group of Command buttons (cmdPlay, cmdRecord, and so on) mimic the buttons used to operate a VCR. The software VCR also contains a clock (lblTime), a channel
indicator (lblChannel), function indicators (shpPlay, shpRecord, and so on), and a "picture tube" (picTV). The event procedures for all of these objects are contained in the Vcr.frm form
module.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconbeforeyoustartcoding.asp (1 of 2) [11/17/2002 10:41:30 PM]


Welcome to the MSDN Library

Figure 5.3 The main form for the VCR application

In many cases there are repetitive procedures that are shared by more than one object. For example, when the Play, Rewind, or Record buttons are "pushed," the Pause and Stop buttons
need to be enabled. Rather than repeat this code in each button's Click event procedure, it's better to create a shared Sub procedure that can be called by any button. If these procedures need
to be modified in the future, all of the modifications can be done in one place. This and other shared procedures are contained in the standard module, Vcr.bas.

Some parts of a VCR aren't visible, such as the tape transport mechanism or the logic for recording a television program. Likewise, some of the functions of the software VCR have no visual
representation. These are implemented as two class modules: Recorder.cls and Tape.cls. Code to initiate the "recording" process is contained in the clsRecorder module; code to control the
direction and speed of the "tape" is contained in the clsTape module. The classes defined in these modules have no direct references to any of the objects in the forms. Because they are
independent code modules, they could easily be reused to build an audio recorder without any modifications.

In addition to designing the structure of your code, it's important to establish naming conventions. By default, Visual Basic names the first form in a project Form1, the second Form2, and so
on. If you have several forms in an application, it's a good idea to give them meaningful names to avoid confusion when writing or editing your code. Some suggested naming conventions are
presented in "Visual Basic Coding Conventions."

As you learn more about objects and writing code, you can refer to the VCR sample application for examples of various different coding techniques.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconbeforeyoustartcoding.asp (2 of 2) [11/17/2002 10:41:30 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals

MSDN Library GO
Advanced Search Visual Basic Concepts

Code Writing Mechanics

See Also

Up One Level Before you begin, it's important to understand the mechanics of writing code in Visual Basic. Like any programming language, Visual Basic has its own rules for organizing, editing, and
formatting code.
Code Modules
Using the Code Editor The following topics introduce code modules and procedures, discuss the basics of using the Code Editor, and cover basic rules for writing code.
Code Basics
● Code Modules An introduction to the different types of code modules and the procedures that they contain.
● Using the Code Editor An introduction to working with code using the Code Editor.
● Code Basics A discussion of the rules of the Visual Basic language.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcodewritingmechanics.asp [11/17/2002 10:41:35 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals

MSDN Library GO
Advanced Search Visual Basic Concepts

Introduction to Variables, Constants and Data Types

See Also

Up One Level You often need to store values temporarily when performing calculations with Visual Basic. For example, you might want to calculate several values, compare them, and perform different
operations on them, depending on the result of the comparison. You need to retain the values if you want to compare them, but you don't need to store them in a property.
Variables
Understanding the Scope of Variables Visual Basic, like most programming languages, uses variables for storing values. Variables have a name (the word you use to refer to the value the variable contains) and a data type (which
Advanced Variable Topics determines the kind of data the variable can store). Arrays can be used to store indexed collections of related variables.

Static Variables
Constants Constants also store values, but as the name implies, those values remain constant throughout the execution of an application. Using constants can make your code more readable by providing
meaningful names instead of numbers. There are a number of built-in constants in Visual Basic, but you can also create your own.
Data Types
Advanced Variant Topics Data types control the internal storage of data in Visual Basic. By default, Visual Basic uses the Variant data type. There are a number of other available data types that allow you to optimize
Arrays your code for speed and size when you don't need the flexibility that Variant provides.

Dynamic Arrays
For more detailed information, see:

● Variables An introduction to variables: what they are and how to use them.
● Understanding the Scope of Variables A discussion of scope as it applies to variables.
● Advanced Variable Topics Detailed information about variables.
● Static Variables An introduction to using static variables to preserve values.
● Constants An introduction to using constants to represent values.
● Data Types A discussion of the data types available in Visual Basic.
● Advanced Variant Topics Detailed information about the Variant data type.
● Arrays An introduction to the use of arrays for groups of values.
● Dynamic Arrays A discussion of using dynamic arrays to work with groups of values.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconintroductiontovariablesconstantsdatatypes.asp [11/17/2002 10:41:42 PM]


Variables

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and Data
Types

Visual Basic Concepts

Variables

See Also

In Visual Basic, you use variables to temporarily store values during the execution of an application. Variables have a name (the word you use to refer to the value the variable contains) and a
data type (which determines the kind of data the variable can store).

You can think of a variable as a placeholder in memory for an unknown value. For example, imagine you are creating a program for a fruit stand to track the sales of apples. You don't know the
price of an apple or the quantity sold until the sale actually occurs. You can use two variables to hold the unknown values — let's name them ApplePrice and ApplesSold. Each time the program is
run, the user supplies the values for the two variables. To calculate the total sales and display it in a Textbox named txtSales, your code would look like this:

txtSales.txt = ApplePrice * ApplesSold

The expression returns a different total each time, depending on what values the user provides. The variables allow you to make a calculation without having to know in advance what the actual
inputs are.

In this example, the data type of ApplePrice is Currency; the data type of ApplesSold is an integer. Variables can represent many other values as well: text values, dates, various numeric types,
even objects.

Storing and Retrieving Data in Variables

You use assignment statements to perform calculations and assign the result to a variable:

ApplesSold = 10 ' The value 10 is passed to the


' variable.
ApplesSold = ApplesSold + 1 ' The variable is
' incremented.

Note that the equal sign in this example is an assignment operator, not an equality operator; the value (10) is being assigned to the variable (ApplesSold).

Declaring Variables

To declare a variable is to tell the program about it in advance. You declare a variable with the Dim statement, supplying a name for the variable:

Dim variablename [As type]

Variables declared with the Dim statement within a procedure exist only as long as the procedure is executing. When the procedure finishes, the value of the variable disappears. In addition, the
value of a variable in a procedure is local to that procedure — that is, you can't access a variable in one procedure from another procedure. These characteristics allow you to use the same variable
names in different procedures without worrying about conflicts or accidental changes.

A variable name:

● Must begin with a letter.

● Can't contain an embedded period or embedded type-declaration character.

● Must not exceed 255 characters.

● Must be unique within the same scope, which is the range from which the variable can be referenced — a procedure, a form, and so on.

The optional As type clause in the Dim statement allows you to define the data type or object type of the variable you are declaring. Data types define the type of information the variable stores.
Some examples of data types include String, Integer, and Currency. Variables can also contain objects from Visual Basic or other applications. Examples of Visual Basic object types, or classes,
include Object, Form1, and TextBox.

For More Information For more information on objects, see "Programming with Objects" and "Programming with Components." Data types are discussed in detail in the section, "Data Types,"
later in this chapter.

There are other ways to declare variables:

● Declaring a variable in the Declarations section of a form, standard, or class module, rather than within a procedure, makes the variable available to all the procedures in the module.

● Declaring a variable using the Public keyword makes it available throughout your application.

● Declaring a local variable using the Static keyword preserves its value even when a procedure ends.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconvariables.asp?frame=true (1 of 2) [11/17/2002 10:41:47 PM]


Variables

Implicit Declaration

You don't have to declare a variable before using it. For example, you could write a function where you don't need to declare TempVal before using it:

Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TempVal)
End Function

Visual Basic automatically creates a variable with that name, which you can use as if you had explicitly declared it. While this is convenient, it can lead to subtle errors in your code if you misspell a
variable name. For example, suppose that this was the function you wrote:

Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TemVal)
End Function

At first glance, this looks the same. But because the TempVal variable was misspelled on the next-to-last line, this function will always return zero. When Visual Basic encounters a new name, it
can't determine whether you actually meant to implicitly declare a new variable or you just misspelled an existing variable name, so it creates a new variable with that name.

Explicit Declaration

To avoid the problem of misnaming variables, you can stipulate that Visual Basic always warn you whenever it encounters a name not declared explicitly as a variable.

To explicitly declare variables

● Place this statement in the Declarations section of a class, form, or standard module:

Option Explicit

–or–

From the Tools menu, choose Options, click the Editor tab and check the Require Variable Declaration option. This automatically inserts the Option Explicit statement in any new modules, but not in modules already created; therefore, you must manually add
Option Explicit to any existing modules within a project.

Had this statement been in effect for the form or standard module containing the SafeSqr function, Visual Basic would have recognized TempVal and TemVal as undeclared variables and generated
errors for both of them. You could then explicitly declare TempVal:

Function SafeSqr(num)
Dim TempVal
TempVal = Abs(num)
SafeSqr = Sqr(TemVal)
End Function

Now you'd understand the problem immediately because Visual Basic would display an error message for the incorrectly spelled TemVal. Because the Option Explicit statement helps you catch
these kinds of errors, it's a good idea to use it with all your code.

Note The Option Explicit statement operates on a per-module basis; it must be placed in the Declarations section of every form, standard, and class module for which you want Visual Basic to
enforce explicit variable declarations. If you select Require Variable Declaration, Visual Basic inserts Option Explicit in all subsequent form, standard, and class modules, but does not add it to
existing code. You must manually add Option Explicit to any existing modules within a project.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconvariables.asp?frame=true (2 of 2) [11/17/2002 10:41:47 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and
Data Types
MSDN Library GO
Advanced Search
Visual Basic Concepts

Variables

See Also

Up One Level In Visual Basic, you use variables to temporarily store values during the execution of an application. Variables have a name (the word you use to refer to the value the variable contains) and a
Variables data type (which determines the kind of data the variable can store).

Understanding the Scope of Variables


You can think of a variable as a placeholder in memory for an unknown value. For example, imagine you are creating a program for a fruit stand to track the sales of apples. You don't know the
Advanced Variable Topics price of an apple or the quantity sold until the sale actually occurs. You can use two variables to hold the unknown values — let's name them ApplePrice and ApplesSold. Each time the program
is run, the user supplies the values for the two variables. To calculate the total sales and display it in a Textbox named txtSales, your code would look like this:
Static Variables
Constants
Data Types
txtSales.txt = ApplePrice * ApplesSold

Advanced Variant Topics The expression returns a different total each time, depending on what values the user provides. The variables allow you to make a calculation without having to know in advance what the
Arrays actual inputs are.

Dynamic Arrays
In this example, the data type of ApplePrice is Currency; the data type of ApplesSold is an integer. Variables can represent many other values as well: text values, dates, various numeric
types, even objects.

Storing and Retrieving Data in Variables

You use assignment statements to perform calculations and assign the result to a variable:

ApplesSold = 10 ' The value 10 is passed to the


' variable.
ApplesSold = ApplesSold + 1 ' The variable is
' incremented.

Note that the equal sign in this example is an assignment operator, not an equality operator; the value (10) is being assigned to the variable (ApplesSold).

Declaring Variables

To declare a variable is to tell the program about it in advance. You declare a variable with the Dim statement, supplying a name for the variable:

Dim variablename [As type]

Variables declared with the Dim statement within a procedure exist only as long as the procedure is executing. When the procedure finishes, the value of the variable disappears. In addition,
the value of a variable in a procedure is local to that procedure — that is, you can't access a variable in one procedure from another procedure. These characteristics allow you to use the same
variable names in different procedures without worrying about conflicts or accidental changes.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconvariables.asp (1 of 3) [11/17/2002 10:41:50 PM]


Welcome to the MSDN Library

A variable name:

● Must begin with a letter.

● Can't contain an embedded period or embedded type-declaration character.

● Must not exceed 255 characters.

● Must be unique within the same scope, which is the range from which the variable can be referenced — a procedure, a form, and so on.

The optional As type clause in the Dim statement allows you to define the data type or object type of the variable you are declaring. Data types define the type of information the variable
stores. Some examples of data types include String, Integer, and Currency. Variables can also contain objects from Visual Basic or other applications. Examples of Visual Basic object types, or
classes, include Object, Form1, and TextBox.

For More Information For more information on objects, see "Programming with Objects" and "Programming with Components." Data types are discussed in detail in the section, "Data
Types," later in this chapter.

There are other ways to declare variables:

● Declaring a variable in the Declarations section of a form, standard, or class module, rather than within a procedure, makes the variable available to all the procedures in the module.

● Declaring a variable using the Public keyword makes it available throughout your application.

● Declaring a local variable using the Static keyword preserves its value even when a procedure ends.

Implicit Declaration

You don't have to declare a variable before using it. For example, you could write a function where you don't need to declare TempVal before using it:

Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TempVal)
End Function

Visual Basic automatically creates a variable with that name, which you can use as if you had explicitly declared it. While this is convenient, it can lead to subtle errors in your code if you
misspell a variable name. For example, suppose that this was the function you wrote:

Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TemVal)
End Function

At first glance, this looks the same. But because the TempVal variable was misspelled on the next-to-last line, this function will always return zero. When Visual Basic encounters a new name, it
can't determine whether you actually meant to implicitly declare a new variable or you just misspelled an existing variable name, so it creates a new variable with that name.

Explicit Declaration

To avoid the problem of misnaming variables, you can stipulate that Visual Basic always warn you whenever it encounters a name not declared explicitly as a variable.

To explicitly declare variables

● Place this statement in the Declarations section of a class, form, or standard module:

Option Explicit

–or–

From the Tools menu, choose Options, click the Editor tab and check the Require Variable Declaration option. This automatically inserts the Option Explicit statement in any new modules, but not in modules already created; therefore, you must manually
add Option Explicit to any existing modules within a project.

Had this statement been in effect for the form or standard module containing the SafeSqr function, Visual Basic would have recognized TempVal and TemVal as undeclared variables and
generated errors for both of them. You could then explicitly declare TempVal:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconvariables.asp (2 of 3) [11/17/2002 10:41:50 PM]


Welcome to the MSDN Library
Function SafeSqr(num)
Dim TempVal
TempVal = Abs(num)
SafeSqr = Sqr(TemVal)
End Function

Now you'd understand the problem immediately because Visual Basic would display an error message for the incorrectly spelled TemVal. Because the Option Explicit statement helps you catch
these kinds of errors, it's a good idea to use it with all your code.

Note The Option Explicit statement operates on a per-module basis; it must be placed in the Declarations section of every form, standard, and class module for which you want Visual Basic to
enforce explicit variable declarations. If you select Require Variable Declaration, Visual Basic inserts Option Explicit in all subsequent form, standard, and class modules, but does not add it to
existing code. You must manually add Option Explicit to any existing modules within a project.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconvariables.asp (3 of 3) [11/17/2002 10:41:50 PM]


Understanding the Scope of Variables

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and Data
Types

Visual Basic Concepts

Understanding the Scope of Variables

See Also

The scope of a variable defines which parts of your code are aware of its existence. When you declare a variable within a procedure, only code within that procedure can access or change the value
of that variable; it has a scope that is local to that procedure. Sometimes, however, you need to use a variable with a broader scope, such as one whose value is available to all the procedures
within the same module, or even to all the procedures in your entire application. Visual Basic allows you to specify the scope of a variable when you declare it.

Scoping Variables

Depending on how it is declared, a variable is scoped as either a procedure-level (local) or module-level variable.

Scope Private Public

Procedure-level Variables are private to the procedure in which they appear. Not applicable. You cannot declare public variables within a procedure.

Module-level Variables are private to the module in which they appear. Variables are available to all modules.

Variables Used Within a Procedure

Procedure-level variables are recognized only in the procedure in which they're declared. These are also known as local variables. You declare them with the Dim or Static keywords. For example:

Dim intTemp As Integer

–or–

Static intPermanent As Integer

Values in local variables declared with Static exist the entire time your application is running while variables declared with Dim exist only as long as the procedure is executing.

Local variables are a good choice for any kind of temporary calculation. For example, you can create a dozen different procedures containing a variable called intTemp. As long as each intTemp is
declared as a local variable, each procedure recognizes only its own version of intTemp. Any one procedure can alter the value in its local intTemp without affecting intTemp variables in other
procedures.

Variables Used Within a Module

By default, a module-level variable is available to all the procedures in that module, but not to code in other modules. You create module-level variables by declaring them with the Private keyword
in the Declarations section at the top of the module. For example:

Private intTemp As Integer

At the module level, there is no difference between Private and Dim, but Private is preferred because it readily contrasts with Public and makes your code easier to understand.

Variables Used by All Modules

To make a module-level variable available to other modules, use the Public keyword to declare the variable. The values in public variables are available to all procedures in your application. Like all
module-level variables, public variables are declared in the Declarations section at the top of the module. For example:

Public intTemp As Integer

Note You can't declare public variables within a procedure, only within the Declarations section of a module.

For More Information For additional information about variables, see "Advanced Variable Topics."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/en-us/vbcon98/h...vbconunderstandingscopeofvariables.asp?frame=true (1 of 2) [11/17/2002 10:41:55 PM]


Understanding the Scope of Variables

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/h...vbconunderstandingscopeofvariables.asp?frame=true (2 of 2) [11/17/2002 10:41:55 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and
Data Types
MSDN Library GO
Advanced Search
Visual Basic Concepts

Understanding the Scope of Variables

See Also

Up One Level The scope of a variable defines which parts of your code are aware of its existence. When you declare a variable within a procedure, only code within that procedure can access or change the
Variables value of that variable; it has a scope that is local to that procedure. Sometimes, however, you need to use a variable with a broader scope, such as one whose value is available to all the
procedures within the same module, or even to all the procedures in your entire application. Visual Basic allows you to specify the scope of a variable when you declare it.
Understanding the Scope of Variables
Advanced Variable Topics Scoping Variables
Static Variables
Constants Depending on how it is declared, a variable is scoped as either a procedure-level (local) or module-level variable.

Data Types
Advanced Variant Topics Scope Private Public

Arrays
Procedure-level Variables are private to the procedure in which they appear. Not applicable. You cannot declare public variables within a procedure.

Dynamic Arrays
Module-level Variables are private to the module in which they appear. Variables are available to all modules.

Variables Used Within a Procedure

Procedure-level variables are recognized only in the procedure in which they're declared. These are also known as local variables. You declare them with the Dim or Static keywords. For
example:

Dim intTemp As Integer

–or–

Static intPermanent As Integer

Values in local variables declared with Static exist the entire time your application is running while variables declared with Dim exist only as long as the procedure is executing.

Local variables are a good choice for any kind of temporary calculation. For example, you can create a dozen different procedures containing a variable called intTemp. As long as each intTemp
is declared as a local variable, each procedure recognizes only its own version of intTemp. Any one procedure can alter the value in its local intTemp without affecting intTemp variables in
other procedures.

Variables Used Within a Module

By default, a module-level variable is available to all the procedures in that module, but not to code in other modules. You create module-level variables by declaring them with the Private
keyword in the Declarations section at the top of the module. For example:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconunderstandingscopeofvariables.asp (1 of 2) [11/17/2002 10:41:58 PM]


Welcome to the MSDN Library

Private intTemp As Integer

At the module level, there is no difference between Private and Dim, but Private is preferred because it readily contrasts with Public and makes your code easier to understand.

Variables Used by All Modules

To make a module-level variable available to other modules, use the Public keyword to declare the variable. The values in public variables are available to all procedures in your application.
Like all module-level variables, public variables are declared in the Declarations section at the top of the module. For example:

Public intTemp As Integer

Note You can't declare public variables within a procedure, only within the Declarations section of a module.

For More Information For additional information about variables, see "Advanced Variable Topics."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconunderstandingscopeofvariables.asp (2 of 2) [11/17/2002 10:41:58 PM]


Advanced Variable Topics

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and Data
Types

Visual Basic Concepts

Advanced Variable Topics

See Also

Using Multiple Variables with the Same Name

If public variables in different modules share the same name, it's possible to differentiate between them in code by referring to both the module and variable names. For example, if there is a
public Integer variable intX declared in both Form1 and in Module1, you can refer to them as Module1.intX and Form1.intX to get the correct values.

To see how this works, insert two standard modules in a new project and draw three command buttons on a form.

One variable, intX, is declared in the first standard module, Module1. The Test procedure sets its value:

Public intX As Integer ' Declare Module1's intX.


Sub Test()
' Set the value for the intX variable in Module1.
intX = 1
End Sub

The second variable, which has the same name, intX, is declared in the second standard module, Module2. Again, a procedure named Test sets its value:

Public intX As Integer ' Declare Module2's intX.


Sub Test()
' Set the value for the intX variable in Module2.
intX = 2
End Sub

The third intX variable is declared in the form module. And again, a procedure named Test sets its value.

Public intX As Integer ' Declare the form's intX


' variable.
Sub Test()
' Set the value for the intX variable in the form.
intX = 3
End Sub

Each of the three command buttons' Click event procedures calls the appropriate Test procedure and uses MsgBox to display the values of the three variables.

Private Sub Command1_Click()


Module1.Test ' Calls Test in Module1.
MsgBox Module1.intX ' Displays Module1's intX.
End Sub

Private Sub Command2_Click()


Module2.Test ' Calls Test in Module2.
MsgBox Module2.intX ' Displays Module2's intX.
End Sub

Private Sub Command3_Click()


Test ' Calls Test in Form1.
MsgBox intX ' Displays Form1's intX.
End Sub

Run the application and click each of the three command buttons. You'll see the separate references to the three public variables. Notice in the third command button's Click event procedure, you
don't need to specify Form1.Test when calling the form's Test procedure, or Form1.intX when calling the value of the form's Integer variable. If there are multiple procedures and variables with
the same name, Visual Basic takes the value of the more local variable, which in this case, is the Form1 variable.

Public vs. Local Variables

You can also have a variable with the same name at a different scope. For example, you could have a public variable named Temp and then, within a procedure, declare a local variable named
Temp. References to the name Temp within the procedure would access the local variable; references to Temp outside the procedure would access the public variable. The module-level variable can
be accessed from within the procedure by qualifying the variable with the module name.

Public Temp As Integer


Sub Test()
Dim Temp As Integer
Temp = 2 ' Temp has a value of 2.
MsgBox Form1.Temp ' Form1.Temp has a value of 1.
End Sub

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAdvancedVariableTopics.asp?frame=true (1 of 2) [11/17/2002 10:42:06 PM]


Advanced Variable Topics
Private Sub Form_Load()
Temp = 1 ' Set Form1.Temp to 1.
End Sub
Private Sub Command1_Click()
Test
End Sub

In general, when variables have the same name but different scope, the more local variable always shadows (that is, it is accessed in preference to) less local variables. So if you also had a
procedure-level variable named Temp, it would shadow the public variable Temp within that module.

Shadowing Form Properties and Controls

Due to the effect of shadowing, form properties, controls, constants, and procedures are treated as module-level variables in the form module. It is not legal to have a form property or control
with the same name as a module-level variable, constant, user-defined type, or procedure because both are in the same scope.

Within the form module, local variables with the same names as controls on the form shadow the controls. You must qualify the control with a reference to the form or the Me keyword to set or get
its value or any of its properties. For example:

Private Sub Form_Click ()


Dim Text1, BackColor
' Assume there is also a control on the form called
' Text1.
Text1 = "Variable" ' Variable shadows control.
Me.Text1 = "Control" ' Must qualify with Me to get
' control.
Text1.Top = 0 ' This causes an error!
Me.Text1.Top = 0 ' Must qualify with Me to get
' control.
BackColor = 0 ' Variable shadows property.
Me.BackColor = 0 ' Must qualify with Me to get
' form property.
End Sub

Using Variables and Procedures with the Same Name

The names of your private module-level and public module-level variables can also conflict with the names of your procedures. A variable in the module cannot have the same name as any
procedures or types defined in the module. It can, however, have the same name as public procedures, types, or variables defined in other modules. In this case, when the variable is accessed
from another module, it must be qualified with the module name.

While the shadowing rules described above are not complex, shadowing can be confusing and lead to subtle bugs in your code; it is good programming practice to keep the names of your variables
distinct from each other. In form modules, try to use variables names that are different from names of controls on those forms.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAdvancedVariableTopics.asp?frame=true (2 of 2) [11/17/2002 10:42:06 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and
Data Types
MSDN Library GO
Advanced Search
Visual Basic Concepts

Advanced Variable Topics

See Also

Up One Level Using Multiple Variables with the Same Name


Variables
Understanding the Scope of Variables If public variables in different modules share the same name, it's possible to differentiate between them in code by referring to both the module and variable names. For example, if there is a
public Integer variable intX declared in both Form1 and in Module1, you can refer to them as Module1.intX and Form1.intX to get the correct values.
Advanced Variable Topics
Static Variables To see how this works, insert two standard modules in a new project and draw three command buttons on a form.
Constants
Data Types One variable, intX, is declared in the first standard module, Module1. The Test procedure sets its value:
Advanced Variant Topics
Arrays Public intX As Integer ' Declare Module1's intX.
Dynamic Arrays Sub Test()
' Set the value for the intX variable in Module1.
intX = 1
End Sub

The second variable, which has the same name, intX, is declared in the second standard module, Module2. Again, a procedure named Test sets its value:

Public intX As Integer ' Declare Module2's intX.


Sub Test()
' Set the value for the intX variable in Module2.
intX = 2
End Sub

The third intX variable is declared in the form module. And again, a procedure named Test sets its value.

Public intX As Integer ' Declare the form's intX


' variable.
Sub Test()
' Set the value for the intX variable in the form.
intX = 3
End Sub

Each of the three command buttons' Click event procedures calls the appropriate Test procedure and uses MsgBox to display the values of the three variables.

Private Sub Command1_Click()


Module1.Test ' Calls Test in Module1.
MsgBox Module1.intX ' Displays Module1's intX.
End Sub

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAdvancedVariableTopics.asp (1 of 3) [11/17/2002 10:42:09 PM]


Welcome to the MSDN Library
Private Sub Command2_Click()
Module2.Test ' Calls Test in Module2.
MsgBox Module2.intX ' Displays Module2's intX.
End Sub

Private Sub Command3_Click()


Test ' Calls Test in Form1.
MsgBox intX ' Displays Form1's intX.
End Sub

Run the application and click each of the three command buttons. You'll see the separate references to the three public variables. Notice in the third command button's Click event procedure,
you don't need to specify Form1.Test when calling the form's Test procedure, or Form1.intX when calling the value of the form's Integer variable. If there are multiple procedures and
variables with the same name, Visual Basic takes the value of the more local variable, which in this case, is the Form1 variable.

Public vs. Local Variables

You can also have a variable with the same name at a different scope. For example, you could have a public variable named Temp and then, within a procedure, declare a local variable named
Temp. References to the name Temp within the procedure would access the local variable; references to Temp outside the procedure would access the public variable. The module-level variable
can be accessed from within the procedure by qualifying the variable with the module name.

Public Temp As Integer


Sub Test()
Dim Temp As Integer
Temp = 2 ' Temp has a value of 2.
MsgBox Form1.Temp ' Form1.Temp has a value of 1.
End Sub

Private Sub Form_Load()


Temp = 1 ' Set Form1.Temp to 1.
End Sub
Private Sub Command1_Click()
Test
End Sub

In general, when variables have the same name but different scope, the more local variable always shadows (that is, it is accessed in preference to) less local variables. So if you also had a
procedure-level variable named Temp, it would shadow the public variable Temp within that module.

Shadowing Form Properties and Controls

Due to the effect of shadowing, form properties, controls, constants, and procedures are treated as module-level variables in the form module. It is not legal to have a form property or control
with the same name as a module-level variable, constant, user-defined type, or procedure because both are in the same scope.

Within the form module, local variables with the same names as controls on the form shadow the controls. You must qualify the control with a reference to the form or the Me keyword to set or
get its value or any of its properties. For example:

Private Sub Form_Click ()


Dim Text1, BackColor
' Assume there is also a control on the form called
' Text1.
Text1 = "Variable" ' Variable shadows control.
Me.Text1 = "Control" ' Must qualify with Me to get
' control.
Text1.Top = 0 ' This causes an error!
Me.Text1.Top = 0 ' Must qualify with Me to get
' control.
BackColor = 0 ' Variable shadows property.
Me.BackColor = 0 ' Must qualify with Me to get
' form property.
End Sub

Using Variables and Procedures with the Same Name

The names of your private module-level and public module-level variables can also conflict with the names of your procedures. A variable in the module cannot have the same name as any
procedures or types defined in the module. It can, however, have the same name as public procedures, types, or variables defined in other modules. In this case, when the variable is accessed
from another module, it must be qualified with the module name.

While the shadowing rules described above are not complex, shadowing can be confusing and lead to subtle bugs in your code; it is good programming practice to keep the names of your
variables distinct from each other. In form modules, try to use variables names that are different from names of controls on those forms.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAdvancedVariableTopics.asp (2 of 3) [11/17/2002 10:42:09 PM]


Welcome to the MSDN Library
Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAdvancedVariableTopics.asp (3 of 3) [11/17/2002 10:42:09 PM]


Static Variables

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and Data
Types

Visual Basic Concepts

Static Variables

See Also

In addition to scope, variables have a lifetime, the period of time during which they retain their value. The values in module-level and public variables are preserved for the lifetime of your
application. However, local variables declared with Dim exist only while the procedure in which they are declared is executing. Usually, when a procedure is finished executing, the values of its
local variables are not preserved and the memory used by the local variables is reclaimed. The next time the procedure is executed, all its local variables are reinitialized.

However, you can preserve the value of a local variable by making the variable static. Use the Static keyword to declare one or more variables inside a procedure, exactly as you would with the
Dim statement:

Static Depth

For example, the following function calculates a running total by adding a new value to the total of previous values stored in the static variable Accumulate:

Function RunningTotal(num)
Static ApplesSold
ApplesSold = ApplesSold + num
RunningTotal = ApplesSold
End Function

If ApplesSold was declared with Dim instead of Static, the previous accumulated values would not be preserved across calls to the function, and the function would simply return the same value
with which it was called.

You can produce the same result by declaring ApplesSold in the Declarations section of the module, making it a module-level variable. Once you change the scope of a variable this way, however,
the procedure no longer has exclusive access to it. Because other procedures can access and change the value of the variable, the running totals might be unreliable and the code would be more
difficult to maintain.

Declaring All Local Variables as Static

To make all local variables in a procedure static, place the Static keyword at the beginning of a procedure heading. For example:

Static Function RunningTotal(num)

This makes all the local variables in the procedure static regardless of whether they are declared with Static, Dim, Private, or declared implicitly. You can place Static in front of any Sub or Function
procedure heading, including event procedures and those declared as Private.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconstaticvariables.asp?frame=true [11/17/2002 10:42:17 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and
Data Types
MSDN Library GO
Advanced Search
Visual Basic Concepts

Static Variables

See Also

Up One Level In addition to scope, variables have a lifetime, the period of time during which they retain their value. The values in module-level and public variables are preserved for the lifetime of your
Variables application. However, local variables declared with Dim exist only while the procedure in which they are declared is executing. Usually, when a procedure is finished executing, the values of its
local variables are not preserved and the memory used by the local variables is reclaimed. The next time the procedure is executed, all its local variables are reinitialized.
Understanding the Scope of Variables
Advanced Variable Topics However, you can preserve the value of a local variable by making the variable static. Use the Static keyword to declare one or more variables inside a procedure, exactly as you would with the
Dim statement:
Static Variables
Constants
Data Types
Static Depth

Advanced Variant Topics For example, the following function calculates a running total by adding a new value to the total of previous values stored in the static variable Accumulate:
Arrays
Dynamic Arrays Function RunningTotal(num)
Static ApplesSold
ApplesSold = ApplesSold + num
RunningTotal = ApplesSold
End Function

If ApplesSold was declared with Dim instead of Static, the previous accumulated values would not be preserved across calls to the function, and the function would simply return the same
value with which it was called.

You can produce the same result by declaring ApplesSold in the Declarations section of the module, making it a module-level variable. Once you change the scope of a variable this way,
however, the procedure no longer has exclusive access to it. Because other procedures can access and change the value of the variable, the running totals might be unreliable and the code
would be more difficult to maintain.

Declaring All Local Variables as Static

To make all local variables in a procedure static, place the Static keyword at the beginning of a procedure heading. For example:

Static Function RunningTotal(num)

This makes all the local variables in the procedure static regardless of whether they are declared with Static, Dim, Private, or declared implicitly. You can place Static in front of any Sub or
Function procedure heading, including event procedures and those declared as Private.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconstaticvariables.asp (1 of 2) [11/17/2002 10:42:19 PM]


Welcome to the MSDN Library
Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconstaticvariables.asp (2 of 2) [11/17/2002 10:42:19 PM]


Constants

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and Data
Types

Visual Basic Concepts

Constants

See Also

Often you'll find that your code contains constant values that reappear over and over. Or you may find that the code depends on certain numbers that are difficult to remember — numbers that, in
and of themselves, have no obvious meaning.

In these cases, you can greatly improve the readability of your code — and make it easier to maintain — by using constants. A constant is a meaningful name that takes the place of a number or
string that does not change. Although a constant somewhat resembles a variable, you can't modify a constant or assign a new value to it as you can to a variable. There are two sources for
constants:

● Intrinsic or system-defined constants are provided by applications and controls. Visual Basic constants are listed in the Visual Basic (VB) and Visual Basic for applications (VBA) object libraries in the Object Browser. Other applications that provide object libraries,
such as Microsoft Excel and Microsoft Project, also provide a list of constants you can use with their objects, methods, and properties. Constants are also defined in the object library for each ActiveX control. For details on using the Object Browser, see
"Programming with Objects."

● Symbolic or user-defined constants are declared using the Const statement. User-defined constants are described in the next section, "Creating Your Own Constants."

In Visual Basic, constant names are in a mixed-case format, with a prefix indicating the object library that defines the constant. Constants from the Visual Basic and Visual Basic for applications
object libraries are prefaced with "vb" — for instance, vbTileHorizontal.

The prefixes are intended to prevent accidental collisions in cases where constants have identical names and represent different values. Even with prefixes, it's still possible that two object libraries
may contain identical constants representing different values. Which constant is referenced in this case depends on which object library has the higher priority. For information on changing the
priority of object libraries, see the "References Dialog Box."

To be absolutely sure you avoid constant name collisions, you can qualify references to constants with the following syntax:

[libname.][modulename.]constname

Libname is usually the class name of the control or library. Modulename is the name of the module that defines the constant. Constname is the name of the constant. Each of these elements is
defined in the object library, and can be viewed in the Object Browser.

Creating Your Own Constants

The syntax for declaring a constant is:

[Public|Private] Const constantname[As type] = expression

The argument constantname is a valid symbolic name (the rules are the same as those for creating variable names), and expression is composed of numeric or string constants and operators;
however, you can't use function calls in expression.

A Const statement can represent a mathematical or date/time quantity:

Const conPi = 3.14159265358979


Public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #1/1/95#

The Const statement can also be used to define string constants:

Public Const conVersion = "07.10.A"


Const conCodeName = "Enigma"

You can place more than one constant declaration on a single line if you separate them with commas:

Public Const conPi = 3.14, conMaxPlanets = 9, _


conWorldPop = 6E+09

The expression on the right side of the equal sign ( = ) is often a number or literal string, but it can also be an expression that results in a number or string (although that expression can't contain
calls to functions). You can even define constants in terms of previously defined constants:

Const conPi2 = conPi * 2

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconconstants.asp?frame=true (1 of 2) [11/17/2002 10:42:29 PM]


Constants

Once you define constants, you can place them in your code to make it more readable. For example:

Static SolarSystem(1 To conMaxPlanets)


If numPeople > conWorldPop Then Exit Sub

Scoping User-Defined Constants

A Const statement has scope like a variable declaration, and the same rules apply:

● To create a constant that exists only within a procedure, declare it within that procedure.

● To create a constant available to all procedures within a module, but not to any code outside that module, declare it in the Declarations section of the module.

● To create a constant available throughout the application, declare the constant in the Declarations section of a standard module, and place the Public keyword before Const. Public constants cannot be declared in a form or class module.

For More Information For more information regarding scope, see "Understanding the Scope of Variables" earlier in this chapter.

Avoiding Circular References

Because constants can be defined in terms of other constants, you must be careful not to set up a cycle, or circular reference between two or more constants. A cycle occurs when you have two or
more public constants, each of which is defined in terms of the other.

For example:

' In Module 1:
Public Const conA = conB * 2 ' Available throughout
' application.
' In Module 2:
Public Const conB = conA / 2 ' Available throughout
' application.

If a cycle occurs, Visual Basic generates an error when you attempt to run your application. You cannot run your code until you resolve the circular reference. To avoid creating a cycle, restrict all
your public constants to a single module or, at most, a small number of modules.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconconstants.asp?frame=true (2 of 2) [11/17/2002 10:42:29 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and
Data Types
MSDN Library GO
Advanced Search
Visual Basic Concepts

Constants

See Also

Up One Level Often you'll find that your code contains constant values that reappear over and over. Or you may find that the code depends on certain numbers that are difficult to remember — numbers
Variables that, in and of themselves, have no obvious meaning.

Understanding the Scope of Variables


In these cases, you can greatly improve the readability of your code — and make it easier to maintain — by using constants. A constant is a meaningful name that takes the place of a number
Advanced Variable Topics or string that does not change. Although a constant somewhat resembles a variable, you can't modify a constant or assign a new value to it as you can to a variable. There are two sources for
constants:
Static Variables
Constants
Intrinsic or system-defined constants are provided by applications and controls. Visual Basic constants are listed in the Visual Basic (VB) and Visual Basic for applications (VBA) object libraries in the Object Browser. Other applications that provide object
Data Types

libraries, such as Microsoft Excel and Microsoft Project, also provide a list of constants you can use with their objects, methods, and properties. Constants are also defined in the object library for each ActiveX control. For details on using the Object Browser,
see "Programming with Objects."

Advanced Variant Topics ● Symbolic or user-defined constants are declared using the Const statement. User-defined constants are described in the next section, "Creating Your Own Constants."

Arrays
In Visual Basic, constant names are in a mixed-case format, with a prefix indicating the object library that defines the constant. Constants from the Visual Basic and Visual Basic for applications
Dynamic Arrays object libraries are prefaced with "vb" — for instance, vbTileHorizontal.

The prefixes are intended to prevent accidental collisions in cases where constants have identical names and represent different values. Even with prefixes, it's still possible that two object
libraries may contain identical constants representing different values. Which constant is referenced in this case depends on which object library has the higher priority. For information on
changing the priority of object libraries, see the "References Dialog Box."

To be absolutely sure you avoid constant name collisions, you can qualify references to constants with the following syntax:

[libname.][modulename.]constname

Libname is usually the class name of the control or library. Modulename is the name of the module that defines the constant. Constname is the name of the constant. Each of these elements is
defined in the object library, and can be viewed in the Object Browser.

Creating Your Own Constants

The syntax for declaring a constant is:

[Public|Private] Const constantname[As type] = expression

The argument constantname is a valid symbolic name (the rules are the same as those for creating variable names), and expression is composed of numeric or string constants and operators;
however, you can't use function calls in expression.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconconstants.asp (1 of 3) [11/17/2002 10:42:31 PM]


Welcome to the MSDN Library
A Const statement can represent a mathematical or date/time quantity:

Const conPi = 3.14159265358979


Public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #1/1/95#

The Const statement can also be used to define string constants:

Public Const conVersion = "07.10.A"


Const conCodeName = "Enigma"

You can place more than one constant declaration on a single line if you separate them with commas:

Public Const conPi = 3.14, conMaxPlanets = 9, _


conWorldPop = 6E+09

The expression on the right side of the equal sign ( = ) is often a number or literal string, but it can also be an expression that results in a number or string (although that expression can't
contain calls to functions). You can even define constants in terms of previously defined constants:

Const conPi2 = conPi * 2

Once you define constants, you can place them in your code to make it more readable. For example:

Static SolarSystem(1 To conMaxPlanets)


If numPeople > conWorldPop Then Exit Sub

Scoping User-Defined Constants

A Const statement has scope like a variable declaration, and the same rules apply:

● To create a constant that exists only within a procedure, declare it within that procedure.

● To create a constant available to all procedures within a module, but not to any code outside that module, declare it in the Declarations section of the module.

● To create a constant available throughout the application, declare the constant in the Declarations section of a standard module, and place the Public keyword before Const. Public constants cannot be declared in a form or class module.

For More Information For more information regarding scope, see "Understanding the Scope of Variables" earlier in this chapter.

Avoiding Circular References

Because constants can be defined in terms of other constants, you must be careful not to set up a cycle, or circular reference between two or more constants. A cycle occurs when you have two
or more public constants, each of which is defined in terms of the other.

For example:

' In Module 1:
Public Const conA = conB * 2 ' Available throughout
' application.
' In Module 2:
Public Const conB = conA / 2 ' Available throughout
' application.

If a cycle occurs, Visual Basic generates an error when you attempt to run your application. You cannot run your code until you resolve the circular reference. To avoid creating a cycle, restrict
all your public constants to a single module or, at most, a small number of modules.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconconstants.asp (2 of 3) [11/17/2002 10:42:31 PM]


Welcome to the MSDN Library
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconconstants.asp (3 of 3) [11/17/2002 10:42:31 PM]


Data Types

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and Data
Types

Visual Basic Concepts

Data Types

See Also

Variables are placeholders used to store values; they have names and data types. The data type of a variable determines how the bits representing those values are stored in the computer's
memory. When you declare a variable, you can also supply a data type for it. All variables have a data type that determines what kind of data they can store.

By default, if you don't supply a data type, the variable is given the Variant data type. The Variant data type is like a chameleon — it can represent many different data types in different situations.
You don't have to convert between these types of data when assigning them to a Variant variable: Visual Basic automatically performs any necessary conversion.

If you know that a variable will always store data of a particular type, however, Visual Basic can handle that data more efficiently if you declare a variable of that type. For example, a variable to
store a person's name is best represented as a string data type, because a name is always composed of characters.

Data types apply to other things besides variables. When you assign a value to a property, that value has a data type; arguments to functions also have data types. In fact, just about anything in
Visual Basic that involves data also involves data types.

You can also declare arrays of any of the fundamental types.

For More Information For more information, see the section, "Arrays," later in this chapter. Selecting data types to improve your application's performance is discussed in "Designing for
Performance and Compatibility."

Declaring Variables with Data Types

Before using a non-Variant variable, you must use the Private, Public, Dim or Static statement to declare it As type. For example, the following statements declare an Integer, Double, String, and
Currency type, respectively:

Private I As Integer
Dim Amt As Double
Static YourName As String
Public BillsPaid As Currency

A Declaration statement can combine multiple declarations, as in these statements:

Private I As Integer, Amt As Double


Private YourName As String, BillsPaid As Currency
Private Test, Amount, J As Integer

Note If you do not supply a data type, the variable is given the default type. In the preceding example, the variables Test and Amount are of the Variant data type. This may surprise you if your
experience with other programming languages leads you to expect all variables in the same declaration statement to have the same specified type (in this case, Integer).

Numeric Data Types

Visual Basic supplies several numeric data types — Integer, Long (long integer), Single (single-precision floating point), Double (double-precision floating point), and Currency. Using a numeric
data type generally uses less storage space than a variant.

If you know that a variable will always store whole numbers (such as 12) rather than numbers with a fractional amount (such as 3.57), declare it as an Integer or Long type. Operations are faster
with integers, and these types consume less memory than other data types. They are especially useful as the counter variables in For...Next loops.

For More Information To read more about control structures, see "Introduction to Control Structures" later in this chapter.

If the variable contains a fraction, declare it as a Single, Double, or Currency variable. The Currency data type supports up to four digits to the right of the decimal separator and fifteen digits to
the left; it is an accurate fixed-point data type suitable for monetary calculations. Floating-point (Single and Double) numbers have much larger ranges than Currency, but can be subject to small
rounding errors.

Note Floating-point values can be expressed as mmmEeee or mmmDeee, in which mmm is the mantissa and eee is the exponent (a power of 10). The highest positive value of a Single data
type is 3.402823E+38, or 3.4 times 10 to the 38th power; the highest positive value of a Double data type is 1.79769313486232D+308, or about 1.8 times 10 to the 308th power. Using D to
separate the mantissa and exponent in a numeric literal causes the value to be treated as a Double data type. Likewise, using E in the same fashion treats the value as a Single data type.

The Byte Data Type

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcondatatypes.asp?frame=true (1 of 5) [11/17/2002 10:42:37 PM]


Data Types

If the variable contains binary data, declare it as an array of the Byte data type. (Arrays are discussed in "Arrays" later in this chapter). Using Byte variables to store binary data preserves it
during format conversions. When String variables are converted between ANSI and Unicode formats, any binary data in the variable is corrupted. Visual Basic may automatically convert between
ANSI and Unicode when:

● Reading from files

● Writing to files

● Calling DLLs

● Calling methods and properties on objects

All operators that work on integers work with the Byte data type except unary minus. Since Byte is an unsigned type with the range 0-255, it cannot represent a negative number. So for unary
minus, Visual Basic coerces the Byte to a signed integer first.

All numeric variables can be assigned to each other and to variables of the Variant type. Visual Basic rounds off rather than truncates the fractional part of a floating-point number before assigning
it to an integer.

For More Information For details on Unicode and ANSI conversions, see "International Issues."

The String Data Type

If you have a variable that will always contain a string and never a numeric value, you can declare it to be of type String:

Private S As String

You can then assign strings to this variable and manipulate it using string functions:

S = "Database"
S = Left(S, 4)

By default, a string variable or argument is a variable-length string; the string grows or shrinks as you assign new data to it. You can also declare strings that have a fixed length. You specify a
fixed-length string with this syntax:

String * size

For example, to declare a string that is always 50 characters long, use code like this:

Dim EmpName As String * 50

If you assign a string of fewer than 50 characters, EmpName is padded with enough trailing spaces to total 50 characters. If you assign a string that is too long for the fixed-length string, Visual
Basic simply truncates the characters.

Because fixed-length strings are padded with trailing spaces, you may find the Trim and RTrim functions, which remove the spaces, useful when working with them.

Fixed-length strings in standard modules can be declared as Public or Private. In forms and class modules, fixed-length strings must be declared Private.

For More Information See "Ltrim, RTrim Function and Trim Functions" in the Language Reference.

Exchanging Strings and Numbers

You can assign a string to a numeric variable if the string represents a numeric value. It's also possible to assign a numeric value to a string variable. For example, place a command button, text
box, and list box on a form. Enter the following code in the command button's Click event. Run the application, and click the command button.

Private Sub Command1_Click()


Dim intX As Integer
Dim strY As String
strY = "100.23"
intX = strY ' Passes the string to a numeric
' variable.
List1.AddItem Cos(strY) ' Adds cosine of number in
' the string to the listbox.
strY = Cos(strY) ' Passes cosine to the
' string variable.
Text1.Text = strY ' String variable prints in
' the text box.
End Sub

Visual Basic will automatically coerce the variables to the appropriate data type. You should use caution when exchanging strings and numbers; passing a non-numeric value in the string will cause
a run-time error to occur.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcondatatypes.asp?frame=true (2 of 5) [11/17/2002 10:42:37 PM]


Data Types

The Boolean Data Type

If you have a variable that will contain simple true/false, yes/no, or on/off information, you can declare it to be of type Boolean. The default value of Boolean is False. In the following example,
blnRunning is a Boolean variable which stores a simple yes/no setting.

Dim blnRunning As Boolean


' Check to see if the tape is running.
If Recorder.Direction = 1 Then
blnRunning = True
End if

The Date Data Type

Date and time values can be contained both in the specific Date data type and in Variant variables. The same general characteristics apply to dates in both types.

For More Information See the section, "Date/Time Values Stored in Variants," in "Advanced Variant Topics."

When other numeric data types are converted to Date, values to the left of the decimal represent date information, while values to the right of the decimal represent time. Midnight is 0, and
midday is 0.5. Negative whole numbers represent dates before December 30, 1899.

The Object Data Type

Object variables are stored as 32-bit (4-byte) addresses that refer to objects within an application or within some other application. A variable declared as Object is one that can subsequently be
assigned (using the Set statement) to refer to any actual object recognized by the application.

Dim objDb As Object


Set objDb = OpenDatabase("c:\Vb5\Biblio.mdb")

When declaring object variables, try to use specific classes (such as TextBox instead of Control or, in the preceding case, Database instead of Object) rather than the generic Object. Visual Basic
can resolve references to the properties and methods of objects with specific types before you run an application. This allows the application to perform faster at run time. Specific classes are
listed in the Object Browser.

When working with other applications' objects, instead of using a Variant or the generic Object, declare objects as they are listed in the Classes list in the Object Browser. This ensures that Visual
Basic recognizes the specific type of object you're referencing, allowing the reference to be resolved at run time.

For More Information For more information on creating and assigning objects and object variables, see "Creating Objects" later in this chapter.

Converting Data Types

Visual Basic provides several conversion functions you can use to convert values into a specific data type. To convert a value to Currency, for example, you use the CCur function:

PayPerWeek = CCur(hours * hourlyPay)

Conversion Converts an expression to


function

Cbool Boolean

Cbyte Byte

Ccur Currency

Cdate Date

CDbl Double

Cint Integer

CLng Long

CSng Single

CStr String

Cvar Variant

CVErr Error

Note Values passed to a conversion function must be valid for the destination data type or an error occurs. For example, if you attempt to convert a Long to an Integer, the Long must be within

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcondatatypes.asp?frame=true (3 of 5) [11/17/2002 10:42:37 PM]


Data Types

the valid range for the Integer data type.

For More Information See the Language Reference for a specific conversion function.

The Variant Data Type

A Variant variable is capable of storing all system-defined types of data. You don't have to convert between these types of data if you assign them to a Variant variable; Visual Basic automatically
performs any necessary conversion. For example:

Dim SomeValue ' Variant by default.


SomeValue = "17" ' SomeValue contains "17" (a two-
' character string).
SomeValue = SomeValue - 15 ' SomeValue now contains
' the numeric value 2.
SomeValue = "U" & SomeValue ' SomeValue now contains
' "U2" (a two- character string).

While you can perform operations on Variant variables without much concern for the kind of data they contain, there are some traps you must avoid.

● If you perform arithmetic operations or functions on a Variant, the Variant must contain something that is a number. For details, see the section, "Numeric Values Stored in Variants," in "Advanced Variant Topics."

● If you are concatenating strings, use the & operator instead of the + operator. For details, see the section, "Strings Stored in Variants," in "Advanced Variant Topics."

In addition to being able to act like the other standard data types, Variants can also contain three special values: Empty, Null, and Error.

The Empty Value

Sometimes you need to know if a value has ever been assigned to a created variable. A Variant variable has the Empty value before it is assigned a value. The Empty value is a special value
different from 0, a zero-length string (""), or the Null value. You can test for the Empty value with the IsEmpty function:

If IsEmpty(Z) Then Z = 0

When a Variant contains the Empty value, you can use it in expressions; it is treated as either 0 or a zero-length string, depending on the expression.

The Empty value disappears as soon as any value (including 0, a zero-length string, or Null) is assigned to a Variant variable. You can set a Variant variable back to Empty by assigning the
keyword Empty to the Variant.

The Null Value

The Variant data type can contain another special value: Null. Null is commonly used in database applications to indicate unknown or missing data. Because of the way it is used in databases, Null
has some unique characteristics:

● Expressions involving Null always result in Null. Thus, Null is said to "propagate" through expressions; if any part of the expression evaluates to Null, the entire expression evaluates to Null.

● Passing Null, a Variant containing Null, or an expression that evaluates to Null as an argument to most functions causes the function to return Null.

● Null values propagate through intrinsic functions that return Variant data types.

You can also assign Null with the Null keyword:

Z = Null

You can use the IsNull function to test if a Variant variable contains Null:

If IsNull(X) And IsNull(Y) Then


Z = Null
Else
Z = 0
End If

If you assign Null to a variable of any type other than Variant, a trappable error occurs. Assigning Null to a Variant variable doesn't cause an error, and Null will propagate through expressions
involving Variant variables (though Null does not propagate through certain functions). You can return Null from any Function procedure with a Variant return value.

Variables are not set to Null unless you explicitly assign Null to them, so if you don't use Null in your application, you don't have to write code that tests for and handles it.

For More Information For information on how to use Null in expressions, see "Null" in the Language Reference.

The Error Value

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcondatatypes.asp?frame=true (4 of 5) [11/17/2002 10:42:37 PM]


Data Types

In a Variant, Error is a special value used to indicate that an error condition has occurred in a procedure. However, unlike for other kinds of errors, normal application-level error handling does not
occur. This allows you, or the application itself, to take some alternative based on the error value. Error values are created by converting real numbers to error values using the CVErr function.

For More Information For information on how to use the Error value in expressions, see "CVErr Function" in the Language Reference. For information on error handling, see "Debugging Your
Code and Handling Errors." For additional information about the Variant data type, see "Advanced Variant Topics."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcondatatypes.asp?frame=true (5 of 5) [11/17/2002 10:42:37 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and
Data Types
MSDN Library GO
Advanced Search
Visual Basic Concepts

Data Types

See Also

Up One Level Variables are placeholders used to store values; they have names and data types. The data type of a variable determines how the bits representing those values are stored in the computer's
Variables memory. When you declare a variable, you can also supply a data type for it. All variables have a data type that determines what kind of data they can store.

Understanding the Scope of Variables


By default, if you don't supply a data type, the variable is given the Variant data type. The Variant data type is like a chameleon — it can represent many different data types in different
Advanced Variable Topics situations. You don't have to convert between these types of data when assigning them to a Variant variable: Visual Basic automatically performs any necessary conversion.
Static Variables
Constants If you know that a variable will always store data of a particular type, however, Visual Basic can handle that data more efficiently if you declare a variable of that type. For example, a variable
to store a person's name is best represented as a string data type, because a name is always composed of characters.
Data Types
Advanced Variant Topics
Data types apply to other things besides variables. When you assign a value to a property, that value has a data type; arguments to functions also have data types. In fact, just about anything
Arrays in Visual Basic that involves data also involves data types.

Dynamic Arrays
You can also declare arrays of any of the fundamental types.

For More Information For more information, see the section, "Arrays," later in this chapter. Selecting data types to improve your application's performance is discussed in "Designing for
Performance and Compatibility."

Declaring Variables with Data Types

Before using a non-Variant variable, you must use the Private, Public, Dim or Static statement to declare it As type. For example, the following statements declare an Integer, Double, String,
and Currency type, respectively:

Private I As Integer
Dim Amt As Double
Static YourName As String
Public BillsPaid As Currency

A Declaration statement can combine multiple declarations, as in these statements:

Private I As Integer, Amt As Double


Private YourName As String, BillsPaid As Currency
Private Test, Amount, J As Integer

Note If you do not supply a data type, the variable is given the default type. In the preceding example, the variables Test and Amount are of the Variant data type. This may surprise you if
your experience with other programming languages leads you to expect all variables in the same declaration statement to have the same specified type (in this case, Integer).

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondatatypes.asp (1 of 6) [11/17/2002 10:42:39 PM]


Welcome to the MSDN Library

Numeric Data Types

Visual Basic supplies several numeric data types — Integer, Long (long integer), Single (single-precision floating point), Double (double-precision floating point), and Currency. Using a numeric
data type generally uses less storage space than a variant.

If you know that a variable will always store whole numbers (such as 12) rather than numbers with a fractional amount (such as 3.57), declare it as an Integer or Long type. Operations are
faster with integers, and these types consume less memory than other data types. They are especially useful as the counter variables in For...Next loops.

For More Information To read more about control structures, see "Introduction to Control Structures" later in this chapter.

If the variable contains a fraction, declare it as a Single, Double, or Currency variable. The Currency data type supports up to four digits to the right of the decimal separator and fifteen digits
to the left; it is an accurate fixed-point data type suitable for monetary calculations. Floating-point (Single and Double) numbers have much larger ranges than Currency, but can be subject to
small rounding errors.

Note Floating-point values can be expressed as mmmEeee or mmmDeee, in which mmm is the mantissa and eee is the exponent (a power of 10). The highest positive value of a Single data
type is 3.402823E+38, or 3.4 times 10 to the 38th power; the highest positive value of a Double data type is 1.79769313486232D+308, or about 1.8 times 10 to the 308th power. Using D to
separate the mantissa and exponent in a numeric literal causes the value to be treated as a Double data type. Likewise, using E in the same fashion treats the value as a Single data type.

The Byte Data Type

If the variable contains binary data, declare it as an array of the Byte data type. (Arrays are discussed in "Arrays" later in this chapter). Using Byte variables to store binary data preserves it
during format conversions. When String variables are converted between ANSI and Unicode formats, any binary data in the variable is corrupted. Visual Basic may automatically convert
between ANSI and Unicode when:

● Reading from files

● Writing to files

● Calling DLLs

● Calling methods and properties on objects

All operators that work on integers work with the Byte data type except unary minus. Since Byte is an unsigned type with the range 0-255, it cannot represent a negative number. So for unary
minus, Visual Basic coerces the Byte to a signed integer first.

All numeric variables can be assigned to each other and to variables of the Variant type. Visual Basic rounds off rather than truncates the fractional part of a floating-point number before
assigning it to an integer.

For More Information For details on Unicode and ANSI conversions, see "International Issues."

The String Data Type

If you have a variable that will always contain a string and never a numeric value, you can declare it to be of type String:

Private S As String

You can then assign strings to this variable and manipulate it using string functions:

S = "Database"
S = Left(S, 4)

By default, a string variable or argument is a variable-length string; the string grows or shrinks as you assign new data to it. You can also declare strings that have a fixed length. You specify a
fixed-length string with this syntax:

String * size

For example, to declare a string that is always 50 characters long, use code like this:

Dim EmpName As String * 50

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondatatypes.asp (2 of 6) [11/17/2002 10:42:39 PM]


Welcome to the MSDN Library

If you assign a string of fewer than 50 characters, EmpName is padded with enough trailing spaces to total 50 characters. If you assign a string that is too long for the fixed-length string, Visual
Basic simply truncates the characters.

Because fixed-length strings are padded with trailing spaces, you may find the Trim and RTrim functions, which remove the spaces, useful when working with them.

Fixed-length strings in standard modules can be declared as Public or Private. In forms and class modules, fixed-length strings must be declared Private.

For More Information See "Ltrim, RTrim Function and Trim Functions" in the Language Reference.

Exchanging Strings and Numbers

You can assign a string to a numeric variable if the string represents a numeric value. It's also possible to assign a numeric value to a string variable. For example, place a command button,
text box, and list box on a form. Enter the following code in the command button's Click event. Run the application, and click the command button.

Private Sub Command1_Click()


Dim intX As Integer
Dim strY As String
strY = "100.23"
intX = strY ' Passes the string to a numeric
' variable.
List1.AddItem Cos(strY) ' Adds cosine of number in
' the string to the listbox.
strY = Cos(strY) ' Passes cosine to the
' string variable.
Text1.Text = strY ' String variable prints in
' the text box.
End Sub

Visual Basic will automatically coerce the variables to the appropriate data type. You should use caution when exchanging strings and numbers; passing a non-numeric value in the string will
cause a run-time error to occur.

The Boolean Data Type

If you have a variable that will contain simple true/false, yes/no, or on/off information, you can declare it to be of type Boolean. The default value of Boolean is False. In the following example,
blnRunning is a Boolean variable which stores a simple yes/no setting.

Dim blnRunning As Boolean


' Check to see if the tape is running.
If Recorder.Direction = 1 Then
blnRunning = True
End if

The Date Data Type

Date and time values can be contained both in the specific Date data type and in Variant variables. The same general characteristics apply to dates in both types.

For More Information See the section, "Date/Time Values Stored in Variants," in "Advanced Variant Topics."

When other numeric data types are converted to Date, values to the left of the decimal represent date information, while values to the right of the decimal represent time. Midnight is 0, and
midday is 0.5. Negative whole numbers represent dates before December 30, 1899.

The Object Data Type

Object variables are stored as 32-bit (4-byte) addresses that refer to objects within an application or within some other application. A variable declared as Object is one that can subsequently
be assigned (using the Set statement) to refer to any actual object recognized by the application.

Dim objDb As Object


Set objDb = OpenDatabase("c:\Vb5\Biblio.mdb")

When declaring object variables, try to use specific classes (such as TextBox instead of Control or, in the preceding case, Database instead of Object) rather than the generic Object. Visual

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondatatypes.asp (3 of 6) [11/17/2002 10:42:39 PM]


Welcome to the MSDN Library
Basic can resolve references to the properties and methods of objects with specific types before you run an application. This allows the application to perform faster at run time. Specific classes
are listed in the Object Browser.

When working with other applications' objects, instead of using a Variant or the generic Object, declare objects as they are listed in the Classes list in the Object Browser. This ensures that
Visual Basic recognizes the specific type of object you're referencing, allowing the reference to be resolved at run time.

For More Information For more information on creating and assigning objects and object variables, see "Creating Objects" later in this chapter.

Converting Data Types

Visual Basic provides several conversion functions you can use to convert values into a specific data type. To convert a value to Currency, for example, you use the CCur function:

PayPerWeek = CCur(hours * hourlyPay)

Conversion Converts an expression to


function

Cbool Boolean

Cbyte Byte

Ccur Currency

Cdate Date

CDbl Double

Cint Integer

CLng Long

CSng Single

CStr String

Cvar Variant

CVErr Error

Note Values passed to a conversion function must be valid for the destination data type or an error occurs. For example, if you attempt to convert a Long to an Integer, the Long must be
within the valid range for the Integer data type.

For More Information See the Language Reference for a specific conversion function.

The Variant Data Type

A Variant variable is capable of storing all system-defined types of data. You don't have to convert between these types of data if you assign them to a Variant variable; Visual Basic
automatically performs any necessary conversion. For example:

Dim SomeValue ' Variant by default.


SomeValue = "17" ' SomeValue contains "17" (a two-
' character string).
SomeValue = SomeValue - 15 ' SomeValue now contains
' the numeric value 2.
SomeValue = "U" & SomeValue ' SomeValue now contains
' "U2" (a two- character string).

While you can perform operations on Variant variables without much concern for the kind of data they contain, there are some traps you must avoid.

● If you perform arithmetic operations or functions on a Variant, the Variant must contain something that is a number. For details, see the section, "Numeric Values Stored in Variants," in "Advanced Variant Topics."

● If you are concatenating strings, use the & operator instead of the + operator. For details, see the section, "Strings Stored in Variants," in "Advanced Variant Topics."

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondatatypes.asp (4 of 6) [11/17/2002 10:42:39 PM]


Welcome to the MSDN Library

In addition to being able to act like the other standard data types, Variants can also contain three special values: Empty, Null, and Error.

The Empty Value

Sometimes you need to know if a value has ever been assigned to a created variable. A Variant variable has the Empty value before it is assigned a value. The Empty value is a special value
different from 0, a zero-length string (""), or the Null value. You can test for the Empty value with the IsEmpty function:

If IsEmpty(Z) Then Z = 0

When a Variant contains the Empty value, you can use it in expressions; it is treated as either 0 or a zero-length string, depending on the expression.

The Empty value disappears as soon as any value (including 0, a zero-length string, or Null) is assigned to a Variant variable. You can set a Variant variable back to Empty by assigning the
keyword Empty to the Variant.

The Null Value

The Variant data type can contain another special value: Null. Null is commonly used in database applications to indicate unknown or missing data. Because of the way it is used in databases,
Null has some unique characteristics:

● Expressions involving Null always result in Null. Thus, Null is said to "propagate" through expressions; if any part of the expression evaluates to Null, the entire expression evaluates to Null.

● Passing Null, a Variant containing Null, or an expression that evaluates to Null as an argument to most functions causes the function to return Null.

● Null values propagate through intrinsic functions that return Variant data types.

You can also assign Null with the Null keyword:

Z = Null

You can use the IsNull function to test if a Variant variable contains Null:

If IsNull(X) And IsNull(Y) Then


Z = Null
Else
Z = 0
End If

If you assign Null to a variable of any type other than Variant, a trappable error occurs. Assigning Null to a Variant variable doesn't cause an error, and Null will propagate through expressions
involving Variant variables (though Null does not propagate through certain functions). You can return Null from any Function procedure with a Variant return value.

Variables are not set to Null unless you explicitly assign Null to them, so if you don't use Null in your application, you don't have to write code that tests for and handles it.

For More Information For information on how to use Null in expressions, see "Null" in the Language Reference.

The Error Value

In a Variant, Error is a special value used to indicate that an error condition has occurred in a procedure. However, unlike for other kinds of errors, normal application-level error handling does
not occur. This allows you, or the application itself, to take some alternative based on the error value. Error values are created by converting real numbers to error values using the CVErr
function.

For More Information For information on how to use the Error value in expressions, see "CVErr Function" in the Language Reference. For information on error handling, see "Debugging Your
Code and Handling Errors." For additional information about the Variant data type, see "Advanced Variant Topics."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondatatypes.asp (5 of 6) [11/17/2002 10:42:39 PM]


Welcome to the MSDN Library

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondatatypes.asp (6 of 6) [11/17/2002 10:42:39 PM]


Advanced Variant Topics

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and Data
Types

Visual Basic Concepts

Advanced Variant Topics

See Also

Internal Representation of Values in Variants

Variant variables maintain an internal representation of the values that they store. This representation determines how Visual Basic treats these values when performing comparisons and other
operations. When you assign a value to a Variant variable, Visual Basic uses the most compact representation that accurately records the value. Later operations may cause Visual Basic to change
the representation it is using for a particular variable. (A Variant variable is not a variable with no type; rather, it is a variable that can freely change its type.) These internal representations
correspond to the explicit data types discussed in "Data Types" earlier in this chapter.

Note A variant always takes up 16 bytes, no matter what you store in it. Objects, strings, and arrays are not physically stored in the Variant; in these cases, four bytes of the Variant are used to
hold either an object reference, or a pointer to the string or array. The actual data are stored elsewhere.

Most of the time, you don't have to be concerned with what internal representation Visual Basic is using for a particular variable; Visual Basic handles conversions automatically. If you want to
know what value Visual Basic is using, however, you can use the VarType function.

For example, if you store values with decimal fractions in a Variant variable, Visual Basic always uses the Double internal representation. If you know that your application does not need the high
accuracy (and slower speed) that a Double value supplies, you can speed your calculations by converting the values to Single, or even to Currency:

If VarType(X) = 5 Then X = CSng(X) ' Convert to Single.

With an array variable, the value of VarType is the sum of the array and data type return values. For example, this array contains Double values:

Private Sub Form_Click()


Dim dblSample(2) As Double
MsgBox VarType(dblSample)
End Sub

Future versions of Visual Basic may add additional Variant representations, so any code you write that makes decisions based on the return value of the VarType function should gracefully handle
return values that are not currently defined.

For More Information For information about the VarType function, see "VarType Function" in the Language Reference. To read more about arrays, see "Arrays" later in this chapter. For details
on converting data types, see "Data Types" earlier in this chapter.

Numeric Values Stored in Variants

When you store whole numbers in Variant variables, Visual Basic uses the most compact representation possible. For example, if you store a small number without a decimal fraction, the Variant
uses an Integer representation for the value. If you then assign a larger number, Visual Basic will use a Long value or, if it is very large or has a fractional component, a Double value.

Sometimes you want to use a specific representation for a number. For example, you might want a Variant variable to store a numeric value as Currency to avoid round-off errors in later
calculations. Visual Basic provides several conversion functions that you can use to convert values into a specific type (see "Converting Data Types" earlier in this chapter). To convert a value to
Currency, for example, you use the CCur function:

PayPerWeek = CCur(hours * hourlyPay)

An error occurs if you attempt to perform a mathematical operation or function on a Variant that does not contain a number or something that can be interpreted as a number. For example, you
cannot perform any arithmetic operations on the value U2 even though it contains a numeric character, because the entire value is not a valid number. Likewise, you cannot perform any
calculations on the value 1040EZ; however, you can perform calculations on the values +10 or -1.7E6 because they are valid numbers. For this reason, you often want to determine if a Variant
variable contains a value that can be used as a number. The IsNumeric function performs this task:

Do
anyNumber = InputBox("Enter a number")
Loop Until IsNumeric(anyNumber)
MsgBox "The square root is: " & Sqr(anyNumber)

When Visual Basic converts a representation that is not numeric (such as a string containing a number) to a numeric value, it uses the Regional settings (specified in the Windows Control Panel) to
interpret the thousands separator, decimal separator, and currency symbol.

Thus, if the country setting in the Windows Control Panel is set to United States, Canada, or Australia, these two statements would return true:

IsNumeric("$100")

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAdvancedVariantTopics.asp?frame=true (1 of 3) [11/17/2002 10:42:49 PM]


Advanced Variant Topics
IsNumeric("1,560.50")

While these two statements would return false:

IsNumeric("DM100")
IsNumeric("1.560,50")

However, the reverse would be the case — the first two would return false and the second two true — if the country setting in the Windows Control Panel was set to Germany.

If you assign a Variant containing a number to a string variable or property, Visual Basic converts the representation of the number to a string automatically. If you want to explicitly convert a
number to a string, use the CStr function. You can also use the Format function to convert a number to a string that includes formatting such as currency, thousands separator, and decimal
separator symbols. The Format function automatically uses the appropriate symbols according to the Regional Settings Properties dialog box in the Windows Control Panel.

For More Information See "Format Function" and topics about the conversion functions in the Language Reference. For information on writing code for applications that will be distributed in
foreign markets, see "International Issues."

Strings Stored in Variants

Generally, storing and using strings in Variant variables poses few problems. As mentioned earlier, however, sometimes the result of the + operator can be ambiguous when used with two Variant
values. If both of the Variants contain numbers, the + operator performs addition. If both of the Variants contain strings, then the + operator performs string concatenation. But if one of the
values is represented as a number and the other is represented as a string, the situation becomes more complicated. Visual Basic first attempts to convert the string into a number. If the
conversion is successful, the + operator adds the two values; if unsuccessful, it generates a Type mismatch error.

To make sure that concatenation occurs, regardless of the representation of the value in the variables, use the & operator. For example, the following code:

Sub Form_Click ()
Dim X, Y
X = "6"
Y = "7"
Print X + Y, X & Y
X = 6
Print X + Y, X & Y
End Sub

produces this result on the form:

67 67
13 67

Note Visual Basic stores strings internally as Unicode. For more information on Unicode, see "International Issues."

Date/Time Values Stored in Variants

Variant variables can also contain date/time values. Several functions return date/time values. For example, DateSerial returns the number of days left in the year:

Private Sub Form_Click ()


Dim rightnow, daysleft, hoursleft, minutesleft
rightnow = Now ' Now returns the current date/time.
daysleft = Int(DateSerial(Year(rightnow) _
+ 1, 1, 1) - rightnow)
hoursleft = 24 - Hour(rightnow)
minutesleft = 60 - Minute(rightnow)
Print daysleft & " days left in the year."
Print hoursleft & " hours left in the day."
Print minutesleft & " minutes left in the hour."
End Sub

You can also perform math on date/time values. Adding or subtracting integers adds or subtracts days; adding or subtracting fractions adds or subtracts time. Therefore, adding 20 adds 20 days,
while subtracting 1/24 subtracts one hour.

The range for dates stored in Variant variables is January 1, 0100, to December 31, 9999. Calculations on dates don't take into account the calendar revisions prior to the switch to the Gregorian
calendar, however, so calculations producing date values earlier than the year in which the Gregorian calendar was adopted (1752 in Britain and its colonies at that time; earlier or later in other
countries) will be incorrect.

You can use date/time literals in your code by enclosing them with the number sign (#), in the same way you enclose string literals with double quotation marks (""). For example, you can
compare a Variant containing a date/time value with a literal date:

If SomeDate > #3/6/93# Then

Similarly, you can compare a date/time value with a complete date/time literal:

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAdvancedVariantTopics.asp?frame=true (2 of 3) [11/17/2002 10:42:49 PM]


Advanced Variant Topics
If SomeDate > #3/6/93 1:20pm# Then

If you do not include a time in a date/time literal, Visual Basic sets the time part of the value to midnight (the start of the day). If you do not include a date in a date/time literal, Visual Basic sets
the date part of the value to December 30, 1899.

Visual Basic accepts a wide variety of date and time formats in literals. These are all valid date/time values:

SomeDate = #3-6-93 13:20#


SomeDate = #March 27, 1993 1:20am#
SomeDate = #Apr-2-93#
SomeDate = #4 April 1993#

For More Information For information on handling dates in international formats, see "International Issues."

In the same way that you can use the IsNumeric function to determine if a Variant variable contains a value that can be considered a valid numeric value, you can use the IsDate function to
determine if a Variant contains a value that can be considered a valid date/time value. You can then use the CDate function to convert the value into a date/time value.

For example, the following code tests the Text property of a text box with IsDate. If the property contains text that can be considered a valid date, Visual Basic converts the text into a date and
computes the days left until the end of the year:

Dim SomeDate, daysleft


If IsDate(Text1.Text) Then
SomeDate = CDate(Text1.Text)
daysleft = DateSerial(Year(SomeDate) + _
1, 1, 1) - SomeDate
Text2.Text = daysleft & " days left in the year."
Else
MsgBox Text1.Text & " is not a valid date."
End If

For More Information For information about the various date/time functions, see "Date Function" in the Language Reference.

Objects Stored in Variants

Objects can be stored in Variant variables. This can be useful when you need to gracefully handle a variety of data types, including objects. For example, all the elements in an array must have the
same data type. Setting the data type of an array to Variant allows you to store objects alongside other data types in an array.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAdvancedVariantTopics.asp?frame=true (3 of 3) [11/17/2002 10:42:49 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and
Data Types
MSDN Library GO
Advanced Search
Visual Basic Concepts

Advanced Variant Topics

See Also

Up One Level Internal Representation of Values in Variants


Variables
Understanding the Scope of Variables Variant variables maintain an internal representation of the values that they store. This representation determines how Visual Basic treats these values when performing comparisons and other
operations. When you assign a value to a Variant variable, Visual Basic uses the most compact representation that accurately records the value. Later operations may cause Visual Basic to
Advanced Variable Topics change the representation it is using for a particular variable. (A Variant variable is not a variable with no type; rather, it is a variable that can freely change its type.) These internal
representations correspond to the explicit data types discussed in "Data Types" earlier in this chapter.
Static Variables
Constants Note A variant always takes up 16 bytes, no matter what you store in it. Objects, strings, and arrays are not physically stored in the Variant; in these cases, four bytes of the Variant are used
Data Types to hold either an object reference, or a pointer to the string or array. The actual data are stored elsewhere.

Advanced Variant Topics


Arrays Most of the time, you don't have to be concerned with what internal representation Visual Basic is using for a particular variable; Visual Basic handles conversions automatically. If you want to
know what value Visual Basic is using, however, you can use the VarType function.
Dynamic Arrays
For example, if you store values with decimal fractions in a Variant variable, Visual Basic always uses the Double internal representation. If you know that your application does not need the
high accuracy (and slower speed) that a Double value supplies, you can speed your calculations by converting the values to Single, or even to Currency:

If VarType(X) = 5 Then X = CSng(X) ' Convert to Single.

With an array variable, the value of VarType is the sum of the array and data type return values. For example, this array contains Double values:

Private Sub Form_Click()


Dim dblSample(2) As Double
MsgBox VarType(dblSample)
End Sub

Future versions of Visual Basic may add additional Variant representations, so any code you write that makes decisions based on the return value of the VarType function should gracefully
handle return values that are not currently defined.

For More Information For information about the VarType function, see "VarType Function" in the Language Reference. To read more about arrays, see "Arrays" later in this chapter. For
details on converting data types, see "Data Types" earlier in this chapter.

Numeric Values Stored in Variants

When you store whole numbers in Variant variables, Visual Basic uses the most compact representation possible. For example, if you store a small number without a decimal fraction, the
Variant uses an Integer representation for the value. If you then assign a larger number, Visual Basic will use a Long value or, if it is very large or has a fractional component, a Double value.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAdvancedVariantTopics.asp (1 of 4) [11/17/2002 10:42:51 PM]


Welcome to the MSDN Library
Sometimes you want to use a specific representation for a number. For example, you might want a Variant variable to store a numeric value as Currency to avoid round-off errors in later
calculations. Visual Basic provides several conversion functions that you can use to convert values into a specific type (see "Converting Data Types" earlier in this chapter). To convert a value
to Currency, for example, you use the CCur function:

PayPerWeek = CCur(hours * hourlyPay)

An error occurs if you attempt to perform a mathematical operation or function on a Variant that does not contain a number or something that can be interpreted as a number. For example,
you cannot perform any arithmetic operations on the value U2 even though it contains a numeric character, because the entire value is not a valid number. Likewise, you cannot perform any
calculations on the value 1040EZ; however, you can perform calculations on the values +10 or -1.7E6 because they are valid numbers. For this reason, you often want to determine if a Variant
variable contains a value that can be used as a number. The IsNumeric function performs this task:

Do
anyNumber = InputBox("Enter a number")
Loop Until IsNumeric(anyNumber)
MsgBox "The square root is: " & Sqr(anyNumber)

When Visual Basic converts a representation that is not numeric (such as a string containing a number) to a numeric value, it uses the Regional settings (specified in the Windows Control
Panel) to interpret the thousands separator, decimal separator, and currency symbol.

Thus, if the country setting in the Windows Control Panel is set to United States, Canada, or Australia, these two statements would return true:

IsNumeric("$100")
IsNumeric("1,560.50")

While these two statements would return false:

IsNumeric("DM100")
IsNumeric("1.560,50")

However, the reverse would be the case — the first two would return false and the second two true — if the country setting in the Windows Control Panel was set to Germany.

If you assign a Variant containing a number to a string variable or property, Visual Basic converts the representation of the number to a string automatically. If you want to explicitly convert a
number to a string, use the CStr function. You can also use the Format function to convert a number to a string that includes formatting such as currency, thousands separator, and decimal
separator symbols. The Format function automatically uses the appropriate symbols according to the Regional Settings Properties dialog box in the Windows Control Panel.

For More Information See "Format Function" and topics about the conversion functions in the Language Reference. For information on writing code for applications that will be distributed in
foreign markets, see "International Issues."

Strings Stored in Variants

Generally, storing and using strings in Variant variables poses few problems. As mentioned earlier, however, sometimes the result of the + operator can be ambiguous when used with two
Variant values. If both of the Variants contain numbers, the + operator performs addition. If both of the Variants contain strings, then the + operator performs string concatenation. But if one
of the values is represented as a number and the other is represented as a string, the situation becomes more complicated. Visual Basic first attempts to convert the string into a number. If the
conversion is successful, the + operator adds the two values; if unsuccessful, it generates a Type mismatch error.

To make sure that concatenation occurs, regardless of the representation of the value in the variables, use the & operator. For example, the following code:

Sub Form_Click ()
Dim X, Y
X = "6"
Y = "7"
Print X + Y, X & Y
X = 6
Print X + Y, X & Y
End Sub

produces this result on the form:

67 67
13 67

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAdvancedVariantTopics.asp (2 of 4) [11/17/2002 10:42:51 PM]


Welcome to the MSDN Library
Note Visual Basic stores strings internally as Unicode. For more information on Unicode, see "International Issues."

Date/Time Values Stored in Variants

Variant variables can also contain date/time values. Several functions return date/time values. For example, DateSerial returns the number of days left in the year:

Private Sub Form_Click ()


Dim rightnow, daysleft, hoursleft, minutesleft
rightnow = Now ' Now returns the current date/time.
daysleft = Int(DateSerial(Year(rightnow) _
+ 1, 1, 1) - rightnow)
hoursleft = 24 - Hour(rightnow)
minutesleft = 60 - Minute(rightnow)
Print daysleft & " days left in the year."
Print hoursleft & " hours left in the day."
Print minutesleft & " minutes left in the hour."
End Sub

You can also perform math on date/time values. Adding or subtracting integers adds or subtracts days; adding or subtracting fractions adds or subtracts time. Therefore, adding 20 adds 20
days, while subtracting 1/24 subtracts one hour.

The range for dates stored in Variant variables is January 1, 0100, to December 31, 9999. Calculations on dates don't take into account the calendar revisions prior to the switch to the
Gregorian calendar, however, so calculations producing date values earlier than the year in which the Gregorian calendar was adopted (1752 in Britain and its colonies at that time; earlier or
later in other countries) will be incorrect.

You can use date/time literals in your code by enclosing them with the number sign (#), in the same way you enclose string literals with double quotation marks (""). For example, you can
compare a Variant containing a date/time value with a literal date:

If SomeDate > #3/6/93# Then

Similarly, you can compare a date/time value with a complete date/time literal:

If SomeDate > #3/6/93 1:20pm# Then

If you do not include a time in a date/time literal, Visual Basic sets the time part of the value to midnight (the start of the day). If you do not include a date in a date/time literal, Visual Basic
sets the date part of the value to December 30, 1899.

Visual Basic accepts a wide variety of date and time formats in literals. These are all valid date/time values:

SomeDate = #3-6-93 13:20#


SomeDate = #March 27, 1993 1:20am#
SomeDate = #Apr-2-93#
SomeDate = #4 April 1993#

For More Information For information on handling dates in international formats, see "International Issues."

In the same way that you can use the IsNumeric function to determine if a Variant variable contains a value that can be considered a valid numeric value, you can use the IsDate function to
determine if a Variant contains a value that can be considered a valid date/time value. You can then use the CDate function to convert the value into a date/time value.

For example, the following code tests the Text property of a text box with IsDate. If the property contains text that can be considered a valid date, Visual Basic converts the text into a date and
computes the days left until the end of the year:

Dim SomeDate, daysleft


If IsDate(Text1.Text) Then
SomeDate = CDate(Text1.Text)
daysleft = DateSerial(Year(SomeDate) + _
1, 1, 1) - SomeDate
Text2.Text = daysleft & " days left in the year."
Else
MsgBox Text1.Text & " is not a valid date."
End If

For More Information For information about the various date/time functions, see "Date Function" in the Language Reference.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAdvancedVariantTopics.asp (3 of 4) [11/17/2002 10:42:51 PM]


Welcome to the MSDN Library

Objects Stored in Variants

Objects can be stored in Variant variables. This can be useful when you need to gracefully handle a variety of data types, including objects. For example, all the elements in an array must have
the same data type. Setting the data type of an array to Variant allows you to store objects alongside other data types in an array.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAdvancedVariantTopics.asp (4 of 4) [11/17/2002 10:42:51 PM]


Arrays

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and Data
Types

Visual Basic Concepts

Arrays

See Also

If you have programmed in other languages, you're probably familiar with the concept of arrays. Arrays allow you to refer to a series of variables by the same name and to use a number (an
index) to tell them apart. This helps you create smaller and simpler code in many situations, because you can set up loops that deal efficiently with any number of cases by using the index
number. Arrays have both upper and lower bounds, and the elements of the array are contiguous within those bounds. Because Visual Basic allocates space for each index number, avoid declaring
an array larger than necessary.

Note The arrays discussed in this section are arrays of variables, declared in code. They are different from the control arrays you specify by setting the Index property of controls at design time.
Arrays of variables are always contiguous; unlike control arrays, you cannot load and unload elements from the middle of the array.

All the elements in an array have the same data type. Of course, when the data type is Variant, the individual elements may contain different kinds of data (objects, strings, numbers, and so on).
You can declare an array of any of the fundamental data types, including user-defined types (described in the section, "Creating Your Own Data Types," in "More About Programming") and object
variables (described in "Programming with Objects").

In Visual Basic there are two types of arrays: a fixed-size array which always remains the same size, and a dynamic array whose size can change at run-time. Dynamic arrays are discussed in
more detail in the section "Dynamic Arrays" later in this chapter.

Declaring Fixed-Size Arrays

There are three ways to declare a fixed-size array, depending on the scope you want the array to have:

● To create a public array, use the Public statement in the Declarations section of a module to declare the array.

● To create a module-level array, use the Private statement in the Declarations section of a module to declare the array.

● To create a local array, use the Private statement in a procedure to declare the array.

Setting Upper and Lower Bounds

When declaring an array, follow the array name by the upper bound in parentheses. The upper bound cannot exceed the range of a Long data type (-2,147,483,648 to 2,147,483,647). For
example, these array declarations can appear in the Declarations section of a module:

Dim Counters(14) As Integer ' 15 elements.


Dim Sums(20) As Double ' 21 elements.

To create a public array, you simply use Public in place of Dim:

Public Counters(14) As Integer


Public Sums(20) As Double

The same declarations within a procedure use Dim:

Dim Counters(14) As Integer


Dim Sums(20) As Double

The first declaration creates an array with 15 elements, with index numbers running from 0 to 14. The second creates an array with 21 elements, with index numbers running from 0 to 20. The
default lower bound is 0.

To specify a lower bound, provide it explicitly (as a Long data type) using the To keyword:

Dim Counters(1 To 15) As Integer


Dim Sums(100 To 120) As String

In the preceding declarations, the index numbers of Counters range from 1 to 15, and the index numbers of Sums range from 100 to 120.

Arrays that Contain Other Arrays

It's possible to create a Variant array, and populate it with other arrays of different data types. The following code creates two arrays, one containing integers and the other strings. It then
declares a third Variant array and populates it with the integer and string arrays.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconarrays.asp?frame=true (1 of 2) [11/17/2002 10:42:57 PM]


Arrays

Private Sub Command1_Click()


Dim intX As Integer ' Declare counter variable.
' Declare and populate an integer array.
Dim countersA(5) As Integer
For intX = 0 To 4
countersA(intX) = 5
Next intX
' Declare and populate a string array.
Dim countersB(5) As String
For intX = 0 To 4
countersB(intX) = "hello"
Next intX
Dim arrX(2) As Variant ' Declare a new two-member
' array.
arrX(1) = countersA() ' Populate the array with
' other arrays.
arrX(2) = countersB()
MsgBox arrX(1)(2) ' Display a member of each
' array.
MsgBox arrX(2)(3)
End Sub

Multidimensional Arrays

Sometimes you need to keep track of related information in an array. For example, to keep track of each pixel on your computer screen, you need to refer to its X and Y coordinates. This can be
done using a multidimensional array to store the values.

With Visual Basic, you can declare arrays of multiple dimensions. For example, the following statement declares a two-dimensional 10-by-10 array within a procedure:

Static MatrixA(9, 9) As Double

Either or both dimensions can be declared with explicit lower bounds:

Static MatrixA(1 To 10, 1 To 10) As Double

You can extend this to more than two dimensions. For example:

Dim MultiD(3, 1 To 10, 1 To 15)

This declaration creates an array that has three dimensions with sizes 4 by 10 by 15. The total number of elements is the product of these three dimensions, or 600.

Note When you start adding dimensions to an array, the total storage needed by the array increases dramatically, so use multidimensional arrays with care. Be especially careful with Variant
arrays, because they are larger than other data types.

Using Loops to Manipulate Arrays

You can efficiently process a multidimensional array by using nested For loops. For example, these statements initialize every element in MatrixA to a value based on its location in the array:

Dim I As Integer, J As Integer


Static MatrixA(1 To 10, 1 To 10) As Double
For I = 1 To 10
For J = 1 To 10
MatrixA(I, J) = I * 10 + J
Next J
Next I

For More Information For information about loops, see "Loop Structures" later in this chapter.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconarrays.asp?frame=true (2 of 2) [11/17/2002 10:42:57 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and
Data Types
MSDN Library GO
Advanced Search
Visual Basic Concepts

Arrays

See Also

Up One Level If you have programmed in other languages, you're probably familiar with the concept of arrays. Arrays allow you to refer to a series of variables by the same name and to use a number (an
Variables index) to tell them apart. This helps you create smaller and simpler code in many situations, because you can set up loops that deal efficiently with any number of cases by using the index
number. Arrays have both upper and lower bounds, and the elements of the array are contiguous within those bounds. Because Visual Basic allocates space for each index number, avoid
Understanding the Scope of Variables declaring an array larger than necessary.

Advanced Variable Topics


Note The arrays discussed in this section are arrays of variables, declared in code. They are different from the control arrays you specify by setting the Index property of controls at design
Static Variables time. Arrays of variables are always contiguous; unlike control arrays, you cannot load and unload elements from the middle of the array.
Constants
Data Types All the elements in an array have the same data type. Of course, when the data type is Variant, the individual elements may contain different kinds of data (objects, strings, numbers, and so
on). You can declare an array of any of the fundamental data types, including user-defined types (described in the section, "Creating Your Own Data Types," in "More About Programming") and
Advanced Variant Topics object variables (described in "Programming with Objects").

Arrays
Dynamic Arrays In Visual Basic there are two types of arrays: a fixed-size array which always remains the same size, and a dynamic array whose size can change at run-time. Dynamic arrays are discussed in
more detail in the section "Dynamic Arrays" later in this chapter.

Declaring Fixed-Size Arrays

There are three ways to declare a fixed-size array, depending on the scope you want the array to have:

● To create a public array, use the Public statement in the Declarations section of a module to declare the array.

● To create a module-level array, use the Private statement in the Declarations section of a module to declare the array.

● To create a local array, use the Private statement in a procedure to declare the array.

Setting Upper and Lower Bounds

When declaring an array, follow the array name by the upper bound in parentheses. The upper bound cannot exceed the range of a Long data type (-2,147,483,648 to 2,147,483,647). For
example, these array declarations can appear in the Declarations section of a module:

Dim Counters(14) As Integer ' 15 elements.


Dim Sums(20) As Double ' 21 elements.

To create a public array, you simply use Public in place of Dim:

Public Counters(14) As Integer


Public Sums(20) As Double

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconarrays.asp (1 of 3) [11/17/2002 10:43:00 PM]


Welcome to the MSDN Library
The same declarations within a procedure use Dim:

Dim Counters(14) As Integer


Dim Sums(20) As Double

The first declaration creates an array with 15 elements, with index numbers running from 0 to 14. The second creates an array with 21 elements, with index numbers running from 0 to 20. The
default lower bound is 0.

To specify a lower bound, provide it explicitly (as a Long data type) using the To keyword:

Dim Counters(1 To 15) As Integer


Dim Sums(100 To 120) As String

In the preceding declarations, the index numbers of Counters range from 1 to 15, and the index numbers of Sums range from 100 to 120.

Arrays that Contain Other Arrays

It's possible to create a Variant array, and populate it with other arrays of different data types. The following code creates two arrays, one containing integers and the other strings. It then
declares a third Variant array and populates it with the integer and string arrays.

Private Sub Command1_Click()


Dim intX As Integer ' Declare counter variable.
' Declare and populate an integer array.
Dim countersA(5) As Integer
For intX = 0 To 4
countersA(intX) = 5
Next intX
' Declare and populate a string array.
Dim countersB(5) As String
For intX = 0 To 4
countersB(intX) = "hello"
Next intX
Dim arrX(2) As Variant ' Declare a new two-member
' array.
arrX(1) = countersA() ' Populate the array with
' other arrays.
arrX(2) = countersB()
MsgBox arrX(1)(2) ' Display a member of each
' array.
MsgBox arrX(2)(3)
End Sub

Multidimensional Arrays

Sometimes you need to keep track of related information in an array. For example, to keep track of each pixel on your computer screen, you need to refer to its X and Y coordinates. This can
be done using a multidimensional array to store the values.

With Visual Basic, you can declare arrays of multiple dimensions. For example, the following statement declares a two-dimensional 10-by-10 array within a procedure:

Static MatrixA(9, 9) As Double

Either or both dimensions can be declared with explicit lower bounds:

Static MatrixA(1 To 10, 1 To 10) As Double

You can extend this to more than two dimensions. For example:

Dim MultiD(3, 1 To 10, 1 To 15)

This declaration creates an array that has three dimensions with sizes 4 by 10 by 15. The total number of elements is the product of these three dimensions, or 600.

Note When you start adding dimensions to an array, the total storage needed by the array increases dramatically, so use multidimensional arrays with care. Be especially careful with Variant

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconarrays.asp (2 of 3) [11/17/2002 10:43:00 PM]


Welcome to the MSDN Library
arrays, because they are larger than other data types.

Using Loops to Manipulate Arrays

You can efficiently process a multidimensional array by using nested For loops. For example, these statements initialize every element in MatrixA to a value based on its location in the array:

Dim I As Integer, J As Integer


Static MatrixA(1 To 10, 1 To 10) As Double
For I = 1 To 10
For J = 1 To 10
MatrixA(I, J) = I * 10 + J
Next J
Next I

For More Information For information about loops, see "Loop Structures" later in this chapter.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconarrays.asp (3 of 3) [11/17/2002 10:43:00 PM]


Dynamic Arrays

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and Data
Types

Visual Basic Concepts

Dynamic Arrays

See Also

Sometimes you may not know exactly how large to make an array. You may want to have the capability of changing the size of the array at run time.

A dynamic array can be resized at any time. Dynamic arrays are among the most flexible and convenient features in Visual Basic, and they help you to manage memory efficiently. For example,
you can use a large array for a short time and then free up memory to the system when you're no longer using the array.

The alternative is to declare an array with the largest possible size and then ignore array elements you don't need. However, this approach, if overused, might cause the operating environment to
run low on memory.

To create a dynamic array

1. Declare the array with a Public statement (if you want the array to be public) or Dim statement at the module level (if you want the array to be module level), or a Static or Dim statement in a procedure (if you want the array to be local). You declare the array as
dynamic by giving it an empty dimension list.

Dim DynArray()

2. Allocate the actual number of elements with a ReDim statement.

ReDim DynArray(X + 1)

The ReDim statement can appear only in a procedure. Unlike the Dim and Static statements, ReDim is an executable statement — it makes the application carry out an action at run time.

The ReDim statement supports the same syntax used for fixed arrays. Each ReDim can change the number of elements, as well as the lower and upper bounds, for each dimension. However, the
number of dimensions in the array cannot change.

ReDim DynArray(4 to 12)

For example, the dynamic array Matrix1 is created by first declaring it at the module level:

Dim Matrix1() As Integer

A procedure then allocates space for the array:

Sub CalcValuesNow ()
.
.
.
ReDim Matrix1(19, 29)
End Sub

The ReDim statement shown here allocates a matrix of 20 by 30 integers (at a total size of 600 elements). Alternatively, the bounds of a dynamic array can be set using variables:

ReDim Matrix1(X, Y)

Note You can assign strings to resizable arrays of bytes. An array of bytes can also be assigned to a variable-length string. Be aware that the number of bytes in a string varies among platforms.
On Unicode platforms the same string contains twice as many bytes as it does on a non-Unicode platform.

Preserving the Contents of Dynamic Arrays

Each time you execute the ReDim statement, all the values currently stored in the array are lost. Visual Basic resets the values to the Empty value (for Variant arrays), to zero (for numeric
arrays), to a zero-length string (for string arrays), or to Nothing (for arrays of objects).

This is useful when you want to prepare the array for new data, or when you want to shrink the size of the array to take up minimal memory. Sometimes you may want to change the size of the
array without losing the data in the array. You can do this by using ReDim with the Preserve keyword. For example, you can enlarge an array by one element without losing the values of the
existing elements using the UBound function to refer to the upper bound:

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcondynamicarrays.asp?frame=true (1 of 2) [11/17/2002 10:43:04 PM]


Dynamic Arrays
ReDim Preserve DynArray(UBound(DynArray) + 1)

Only the upper bound of the last dimension in a multidimensional array can be changed when you use the Preserve keyword; if you change any of the other dimensions, or the lower bound of the
last dimension, a run-time error occurs. Thus, you can use code like this:

ReDim Preserve Matrix(10, UBound(Matrix, 2) + 1)

But you cannot use this code:

ReDim Preserve Matrix(UBound(Matrix, 1) + 1, 10)

For More Information For information about dynamic arrays, see "ReDim Statement" in the Language Reference. To learn more about object arrays, see "Programming with Objects."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcondynamicarrays.asp?frame=true (2 of 2) [11/17/2002 10:43:04 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Variables, Constants and
Data Types
MSDN Library GO
Advanced Search
Visual Basic Concepts

Dynamic Arrays

See Also

Up One Level Sometimes you may not know exactly how large to make an array. You may want to have the capability of changing the size of the array at run time.
Variables
Understanding the Scope of Variables A dynamic array can be resized at any time. Dynamic arrays are among the most flexible and convenient features in Visual Basic, and they help you to manage memory efficiently. For
example, you can use a large array for a short time and then free up memory to the system when you're no longer using the array.
Advanced Variable Topics
Static Variables
The alternative is to declare an array with the largest possible size and then ignore array elements you don't need. However, this approach, if overused, might cause the operating environment
Constants to run low on memory.

Data Types
Advanced Variant Topics To create a dynamic array

Arrays
Dynamic Arrays 1. Declare the array with a Public statement (if you want the array to be public) or Dim statement at the module level (if you want the array to be module level), or a Static or Dim statement in a procedure (if you want the array to be local). You declare the
array as dynamic by giving it an empty dimension list.

Dim DynArray()

2. Allocate the actual number of elements with a ReDim statement.

ReDim DynArray(X + 1)

The ReDim statement can appear only in a procedure. Unlike the Dim and Static statements, ReDim is an executable statement — it makes the application carry out an action at run time.

The ReDim statement supports the same syntax used for fixed arrays. Each ReDim can change the number of elements, as well as the lower and upper bounds, for each dimension. However,
the number of dimensions in the array cannot change.

ReDim DynArray(4 to 12)

For example, the dynamic array Matrix1 is created by first declaring it at the module level:

Dim Matrix1() As Integer

A procedure then allocates space for the array:

Sub CalcValuesNow ()
.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondynamicarrays.asp (1 of 2) [11/17/2002 10:43:05 PM]


Welcome to the MSDN Library
.
.
ReDim Matrix1(19, 29)
End Sub

The ReDim statement shown here allocates a matrix of 20 by 30 integers (at a total size of 600 elements). Alternatively, the bounds of a dynamic array can be set using variables:

ReDim Matrix1(X, Y)

Note You can assign strings to resizable arrays of bytes. An array of bytes can also be assigned to a variable-length string. Be aware that the number of bytes in a string varies among
platforms. On Unicode platforms the same string contains twice as many bytes as it does on a non-Unicode platform.

Preserving the Contents of Dynamic Arrays

Each time you execute the ReDim statement, all the values currently stored in the array are lost. Visual Basic resets the values to the Empty value (for Variant arrays), to zero (for numeric
arrays), to a zero-length string (for string arrays), or to Nothing (for arrays of objects).

This is useful when you want to prepare the array for new data, or when you want to shrink the size of the array to take up minimal memory. Sometimes you may want to change the size of
the array without losing the data in the array. You can do this by using ReDim with the Preserve keyword. For example, you can enlarge an array by one element without losing the values of
the existing elements using the UBound function to refer to the upper bound:

ReDim Preserve DynArray(UBound(DynArray) + 1)

Only the upper bound of the last dimension in a multidimensional array can be changed when you use the Preserve keyword; if you change any of the other dimensions, or the lower bound of
the last dimension, a run-time error occurs. Thus, you can use code like this:

ReDim Preserve Matrix(10, UBound(Matrix, 2) + 1)

But you cannot use this code:

ReDim Preserve Matrix(UBound(Matrix, 1) + 1, 10)

For More Information For information about dynamic arrays, see "ReDim Statement" in the Language Reference. To learn more about object arrays, see "Programming with Objects."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondynamicarrays.asp (2 of 2) [11/17/2002 10:43:05 PM]


Code Modules

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Code Writing Mechanics

Visual Basic Concepts

Code Modules

See Also

Code in Visual Basic is stored in modules. There are three kinds of modules: form, standard, and class.

Simple applications can consist of just a single form, and all of the code in the application resides in that form module. As your applications get larger and more sophisticated, you add additional
forms. Eventually you might find that there is common code you want to execute in several forms. You don't want to duplicate the code in both forms, so you create a separate module containing
a procedure that implements the common code. This separate module should be a standard module. Over time, you can build up a library of modules containing shared procedures.

Each standard, class, and form module can contain:

● Declarations. You can place constant, type, variable, and dynamic-link library (DLL) procedure declarations at the module level of form, class or standard modules.

● Procedures. A Sub, Function, or Property procedure contains pieces of code that can be executed as a unit. These are discussed in the section "Procedures" later in this chapter.

Form Modules

Form modules (.FRM file name extension) are the foundation of most Visual Basic applications. They can contain procedures that handle events, general procedures, and form-level declarations of
variables, constants, types, and external procedures. If you were to look at a form module in a text editor, you would also see descriptions of the form and its controls, including their property
settings. The code that you write in a form module is specific to the particular application to which the form belongs; it might also reference other forms or objects within that application.

Standard Modules

Standard modules (.BAS file name extension) are containers for procedures and declarations commonly accessed by other modules within the application. They can contain global (available to the
whole application) or module-level declarations of variables, constants, types, external procedures, and global procedures. The code that you write in a standard module isn't necessarily tied to a
particular application; if you're careful not to reference forms or controls by name, a standard module can be reused in many different applications.

Class Modules

Class modules (.CLS file name extension) are the foundation of object-oriented programming in Visual Basic. You can write code in class modules to create new objects. These new objects can
include your own customized properties and methods. Actually, forms are just class modules that can have controls placed on them and can display form windows.

For More Information For information about writing code in class modules, see "Programming with Objects."

Note The Professional and Enterprise editions of Visual Basic also include ActiveX Documents, ActiveX Designers, and User Controls. These introduce new types of modules with different file
name extensions. From the standpoint of writing code, these modules should be considered the same as form modules.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconcodemodules.asp?frame=true [11/17/2002 10:43:18 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Code Writing Mechanics

MSDN Library GO
Advanced Search Visual Basic Concepts

Code Modules

See Also

Up One Level Code in Visual Basic is stored in modules. There are three kinds of modules: form, standard, and class.

Code Modules
Using the Code Editor Simple applications can consist of just a single form, and all of the code in the application resides in that form module. As your applications get larger and more sophisticated, you add additional
forms. Eventually you might find that there is common code you want to execute in several forms. You don't want to duplicate the code in both forms, so you create a separate module
Code Basics containing a procedure that implements the common code. This separate module should be a standard module. Over time, you can build up a library of modules containing shared procedures.

Each standard, class, and form module can contain:

● Declarations. You can place constant, type, variable, and dynamic-link library (DLL) procedure declarations at the module level of form, class or standard modules.

● Procedures. A Sub, Function, or Property procedure contains pieces of code that can be executed as a unit. These are discussed in the section "Procedures" later in this chapter.

Form Modules

Form modules (.FRM file name extension) are the foundation of most Visual Basic applications. They can contain procedures that handle events, general procedures, and form-level declarations
of variables, constants, types, and external procedures. If you were to look at a form module in a text editor, you would also see descriptions of the form and its controls, including their
property settings. The code that you write in a form module is specific to the particular application to which the form belongs; it might also reference other forms or objects within that
application.

Standard Modules

Standard modules (.BAS file name extension) are containers for procedures and declarations commonly accessed by other modules within the application. They can contain global (available to
the whole application) or module-level declarations of variables, constants, types, external procedures, and global procedures. The code that you write in a standard module isn't necessarily tied
to a particular application; if you're careful not to reference forms or controls by name, a standard module can be reused in many different applications.

Class Modules

Class modules (.CLS file name extension) are the foundation of object-oriented programming in Visual Basic. You can write code in class modules to create new objects. These new objects can
include your own customized properties and methods. Actually, forms are just class modules that can have controls placed on them and can display form windows.

For More Information For information about writing code in class modules, see "Programming with Objects."

Note The Professional and Enterprise editions of Visual Basic also include ActiveX Documents, ActiveX Designers, and User Controls. These introduce new types of modules with different file

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcodemodules.asp (1 of 2) [11/17/2002 10:43:20 PM]


Welcome to the MSDN Library
name extensions. From the standpoint of writing code, these modules should be considered the same as form modules.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcodemodules.asp (2 of 2) [11/17/2002 10:43:20 PM]


Using the Code Editor

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Code Writing Mechanics

Visual Basic Concepts

Using the Code Editor

See Also

The Visual Basic Code Editor is a window where you write most of your code. It is like a highly specialized word processor with a number of features that make writing Visual Basic code a lot
easier. The Code Editor window is shown in Figure 5.4.

Figure 5.4 The Code Editor window

Because you work with Visual Basic code in modules, a separate Code Editor window is opened for each module you select from the Project Explorer. Code within each module is subdivided into
separate sections for each object contained in the module. Switching between sections is accomplished using the Object Listbox. In a form module, the list includes a general section, a section for
the form itself, and a section for each control contained on the form. For a class module, the list includes a general section and a class section; for a standard module only a general section is
shown.

Each section of code can contain several different procedures, accessed using the Procedure Listbox. The procedure list for a form module contains a separate section for each event procedure for
the form or control. For example, the procedure list for a Label control includes sections for the Change, Click, and DblClick events, among others. Class modules list only the event procedures for
the class itself — Initialize and Terminate. Standard modules don't list any event procedures, because a standard module doesn't support events.

The procedure list for a general section of a module contains a single selection — the Declarations section, where you place module-level variable, constant, and DLL declarations. As you add Sub
or Function procedures to a module, those procedures are added in the Procedure Listbox below the Declarations section.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconusingcodeeditor.asp?frame=true (1 of 3) [11/17/2002 10:43:25 PM]


Using the Code Editor

Two different views of your code are available in the Code Editor window. You can choose to view a single procedure at a time, or to view all of the procedures in the module with each procedure
separated from the next by a line (as shown in Figure 5.4). To switch between the two views, use the View Selection buttons in the lower left-hand corner of the editor window.

Automatic Code Completion

Visual Basic makes writing code much easier with features that can automatically fill in statements, properties, and arguments for you. As you enter code, the editor displays lists of appropriate
choices, statement or function prototypes, or values. Options for enabling or disabling these and other code settings are available on the Editor tab of the Options dialog, accessed through the
Options command on the Tools menu.

When you enter the name of a control in your code, the Auto List Members feature presents a drop-down list of properties available for that control (Figure 5.5). Type in the first few letters of the
property name and the name will be selected from the list; the TAB key will complete the typing for you. This option is also helpful when you aren't sure which properties are available for a given
control. Even if you choose to disable the Auto List Members feature, you can still access it with the CTRL+J key combination.

Figure 5.5 The Auto List Members feature

The Auto Quick Info feature displays the syntax for statements and functions (Figure 5.6). When you enter the name of a valid Visual Basic statement or function the syntax is shown immediately
below the current line, with the first argument in bold. After you enter the first argument value, the second argument appears in bold. Auto Quick Info can also be accessed with the CTRL+I key
combination.

Figure 5.6 Auto Quick Info

Bookmarks

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconusingcodeeditor.asp?frame=true (2 of 3) [11/17/2002 10:43:25 PM]


Using the Code Editor

Bookmarks can be used to mark lines of code in the Code Editor so that you can easily return to them later. Commands to toggle bookmarks on or off as well as to navigate existing bookmarks are
available from the Edit, Bookmarks menu item, or from the Edit toolbar

For More Information For more information on key combinations to access these and other functions in the Code Editor window, see "Code Window Keyboard Shortcuts."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconusingcodeeditor.asp?frame=true (3 of 3) [11/17/2002 10:43:25 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Code Writing Mechanics

MSDN Library GO
Advanced Search Visual Basic Concepts

Using the Code Editor

See Also

Up One Level The Visual Basic Code Editor is a window where you write most of your code. It is like a highly specialized word processor with a number of features that make writing Visual Basic code a lot
easier. The Code Editor window is shown in Figure 5.4.
Code Modules
Using the Code Editor Figure 5.4 The Code Editor window
Code Basics

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusingcodeeditor.asp (1 of 4) [11/17/2002 10:43:27 PM]


Welcome to the MSDN Library

Because you work with Visual Basic code in modules, a separate Code Editor window is opened for each module you select from the Project Explorer. Code within each module is subdivided into
separate sections for each object contained in the module. Switching between sections is accomplished using the Object Listbox. In a form module, the list includes a general section, a section
for the form itself, and a section for each control contained on the form. For a class module, the list includes a general section and a class section; for a standard module only a general section
is shown.

Each section of code can contain several different procedures, accessed using the Procedure Listbox. The procedure list for a form module contains a separate section for each event procedure
for the form or control. For example, the procedure list for a Label control includes sections for the Change, Click, and DblClick events, among others. Class modules list only the event
procedures for the class itself — Initialize and Terminate. Standard modules don't list any event procedures, because a standard module doesn't support events.

The procedure list for a general section of a module contains a single selection — the Declarations section, where you place module-level variable, constant, and DLL declarations. As you add
Sub or Function procedures to a module, those procedures are added in the Procedure Listbox below the Declarations section.

Two different views of your code are available in the Code Editor window. You can choose to view a single procedure at a time, or to view all of the procedures in the module with each
procedure separated from the next by a line (as shown in Figure 5.4). To switch between the two views, use the View Selection buttons in the lower left-hand corner of the editor window.

Automatic Code Completion

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusingcodeeditor.asp (2 of 4) [11/17/2002 10:43:27 PM]


Welcome to the MSDN Library

Visual Basic makes writing code much easier with features that can automatically fill in statements, properties, and arguments for you. As you enter code, the editor displays lists of appropriate
choices, statement or function prototypes, or values. Options for enabling or disabling these and other code settings are available on the Editor tab of the Options dialog, accessed through the
Options command on the Tools menu.

When you enter the name of a control in your code, the Auto List Members feature presents a drop-down list of properties available for that control (Figure 5.5). Type in the first few letters of
the property name and the name will be selected from the list; the TAB key will complete the typing for you. This option is also helpful when you aren't sure which properties are available for a
given control. Even if you choose to disable the Auto List Members feature, you can still access it with the CTRL+J key combination.

Figure 5.5 The Auto List Members feature

The Auto Quick Info feature displays the syntax for statements and functions (Figure 5.6). When you enter the name of a valid Visual Basic statement or function the syntax is shown
immediately below the current line, with the first argument in bold. After you enter the first argument value, the second argument appears in bold. Auto Quick Info can also be accessed with the
CTRL+I key combination.

Figure 5.6 Auto Quick Info

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusingcodeeditor.asp (3 of 4) [11/17/2002 10:43:27 PM]


Welcome to the MSDN Library

Bookmarks

Bookmarks can be used to mark lines of code in the Code Editor so that you can easily return to them later. Commands to toggle bookmarks on or off as well as to navigate existing bookmarks
are available from the Edit, Bookmarks menu item, or from the Edit toolbar

For More Information For more information on key combinations to access these and other functions in the Code Editor window, see "Code Window Keyboard Shortcuts."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconusingcodeeditor.asp (4 of 4) [11/17/2002 10:43:27 PM]


Code Basics

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Code Writing Mechanics

Visual Basic Concepts

Code Basics

See Also

This section presents information on code writing mechanics, including breaking and combining lines of code, adding comments to your code, using numbers in code, and following naming
conventions in Visual Basic.

Breaking a Single Statement Into Multiple Lines

You can break a long statement into multiple lines in the Code window using the line-continuation character (a space followed by an underscore). Using this character can make your code easier to
read, both online and when printed. The following code is broken into three lines with line-continuation characters ( _):

Data1.RecordSource = _
"SELECT * FROM Titles, Publishers" _
& "WHERE Publishers.PubId = Titles.PubID" _
& "AND Publishers.State = 'CA'"

You can't follow a line-continuation character with a comment on the same line. There are also some limitations as to where the line-continuation character can be used.

Combining Statements on One Line

There is usually one Visual Basic statement to a line, and there is no statement terminator. However, you can place two or more statements on a line if you use a colon (:) to separate them:

Text1.Text = "Hello" : Red = 255 : Text1.BackColor = _


Red

In order to make your code more readable, however, it's better to place each statement on a separate line.

For More Information For more information, see "Visual Basic Specifications, Limitations, and File Formats."

Adding Comments to Your Code

As you read through the examples in this guide, you'll often come across the comment symbol ('). This symbol tells Visual Basic to ignore the words that follow it. Such words are remarks placed
in the code for the benefit of the developer, and other programmers who might examine the code later. For example:

' This is a comment beginning at the left edge of the


' screen.
Text1.Text = "Hi!" ' Place friendly greeting in text
' box.

Comments can follow a statement on the same line or can occupy an entire line. Both are illustrated in the preceding code. Remember that comments can't follow a line-continuation character on
the same line.

Note You can add or remove comment symbols for a block of code by selecting two or more lines of code and choosing the Comment Block or Uncomment Block buttons on the Edit toolbar.

Understanding Numbering Systems

Most numbers in this documentation are decimal (base 10). But occasionally it's convenient to use hexadecimal numbers (base 16) or octal numbers (base 8). Visual Basic represents numbers in
hexadecimal with the prefix &H and in octal with &O. The following table shows the same numbers in decimal, octal, and hexadecimal.

Decimal Octal Hexadecimal

9 &O11 &H9

15 &O17 &HF

16 &O20 &H10

20 &O24 &H14

255 &O377 &HFF

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconcodebasics.asp?frame=true (1 of 2) [11/17/2002 10:43:31 PM]


Code Basics

You generally don't have to learn the hexadecimal or octal number system yourself because the computer can work with numbers entered in any system. However, some number systems lend
themselves to certain tasks, such as using hexadecimals to set the screen and control colors.

Naming Conventions in Visual Basic

While you are writing Visual Basic code, you declare and name many elements (Sub and Function procedures, variables, constants, and so on). The names of the procedures, variables, and
constants that you declare in your Visual Basic code must follow these guidelines:

● They must begin with a letter.

● They can't contain embedded periods or type-declaration characters (special characters that specify a data type.

● They can be no longer than 255 characters. The names of controls, forms, classes, and modules must not exceed 40 characters.

● They can't be the same as restricted keywords.

A restricted keyword is a word that Visual Basic uses as part of its language. This includes predefined statements (such as If and Loop), functions (such as Len and Abs), and operators (such as Or
and Mod).

For More Information For a complete list of keywords, see the Language Reference.

Your forms and controls can have the same name as a restricted keyword. For example, you can have a control named Loop. In your code you cannot refer to that control in the usual way,
however, because Visual Basic assumes you mean the Loop keyword. For example, this code causes an error:

Loop.Visible = True ' Causes an error.

To refer to a form or control that has the same name as a restricted keyword, you must either qualify it or surround it with square brackets: [ ]. For example, this code does not cause an error:

MyForm.Loop.Visible = True ' Qualified with the form


' name.
[Loop].Visible = True ' Square brackets also
' work.

You can use square brackets in this way when referring to forms and controls, but not when declaring a variable or defining a procedure with the same name as a restricted keyword. Square
brackets can also be used to force Visual Basic to accept names provided by other type libraries that conflict with restricted keywords.

Note Because typing square brackets can get tedious, you might want to refrain from using restricted keywords as the name of forms and controls. However, you can use this technique if a
future version of Visual Basic defines a new keyword that conflicts with an existing form or control name when you update your code to work with the new version.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconcodebasics.asp?frame=true (2 of 2) [11/17/2002 10:43:31 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Code Writing Mechanics

MSDN Library GO
Advanced Search Visual Basic Concepts

Code Basics

See Also

Up One Level This section presents information on code writing mechanics, including breaking and combining lines of code, adding comments to your code, using numbers in code, and following naming
conventions in Visual Basic.
Code Modules
Using the Code Editor Breaking a Single Statement Into Multiple Lines
Code Basics
You can break a long statement into multiple lines in the Code window using the line-continuation character (a space followed by an underscore). Using this character can make your code easier
to read, both online and when printed. The following code is broken into three lines with line-continuation characters ( _):

Data1.RecordSource = _
"SELECT * FROM Titles, Publishers" _
& "WHERE Publishers.PubId = Titles.PubID" _
& "AND Publishers.State = 'CA'"

You can't follow a line-continuation character with a comment on the same line. There are also some limitations as to where the line-continuation character can be used.

Combining Statements on One Line

There is usually one Visual Basic statement to a line, and there is no statement terminator. However, you can place two or more statements on a line if you use a colon (:) to separate them:

Text1.Text = "Hello" : Red = 255 : Text1.BackColor = _


Red

In order to make your code more readable, however, it's better to place each statement on a separate line.

For More Information For more information, see "Visual Basic Specifications, Limitations, and File Formats."

Adding Comments to Your Code

As you read through the examples in this guide, you'll often come across the comment symbol ('). This symbol tells Visual Basic to ignore the words that follow it. Such words are remarks
placed in the code for the benefit of the developer, and other programmers who might examine the code later. For example:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcodebasics.asp (1 of 3) [11/17/2002 10:43:32 PM]


Welcome to the MSDN Library
' This is a comment beginning at the left edge of the
' screen.
Text1.Text = "Hi!" ' Place friendly greeting in text
' box.

Comments can follow a statement on the same line or can occupy an entire line. Both are illustrated in the preceding code. Remember that comments can't follow a line-continuation character
on the same line.

Note You can add or remove comment symbols for a block of code by selecting two or more lines of code and choosing the Comment Block or Uncomment Block buttons on the Edit toolbar.

Understanding Numbering Systems

Most numbers in this documentation are decimal (base 10). But occasionally it's convenient to use hexadecimal numbers (base 16) or octal numbers (base 8). Visual Basic represents numbers
in hexadecimal with the prefix &H and in octal with &O. The following table shows the same numbers in decimal, octal, and hexadecimal.

Decimal Octal Hexadecimal

9 &O11 &H9

15 &O17 &HF

16 &O20 &H10

20 &O24 &H14

255 &O377 &HFF

You generally don't have to learn the hexadecimal or octal number system yourself because the computer can work with numbers entered in any system. However, some number systems lend
themselves to certain tasks, such as using hexadecimals to set the screen and control colors.

Naming Conventions in Visual Basic

While you are writing Visual Basic code, you declare and name many elements (Sub and Function procedures, variables, constants, and so on). The names of the procedures, variables, and
constants that you declare in your Visual Basic code must follow these guidelines:

● They must begin with a letter.

● They can't contain embedded periods or type-declaration characters (special characters that specify a data type.

● They can be no longer than 255 characters. The names of controls, forms, classes, and modules must not exceed 40 characters.

● They can't be the same as restricted keywords.

A restricted keyword is a word that Visual Basic uses as part of its language. This includes predefined statements (such as If and Loop), functions (such as Len and Abs), and operators (such as
Or and Mod).

For More Information For a complete list of keywords, see the Language Reference.

Your forms and controls can have the same name as a restricted keyword. For example, you can have a control named Loop. In your code you cannot refer to that control in the usual way,
however, because Visual Basic assumes you mean the Loop keyword. For example, this code causes an error:

Loop.Visible = True ' Causes an error.

To refer to a form or control that has the same name as a restricted keyword, you must either qualify it or surround it with square brackets: [ ]. For example, this code does not cause an error:

MyForm.Loop.Visible = True ' Qualified with the form


' name.
[Loop].Visible = True ' Square brackets also
' work.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcodebasics.asp (2 of 3) [11/17/2002 10:43:32 PM]


Welcome to the MSDN Library

You can use square brackets in this way when referring to forms and controls, but not when declaring a variable or defining a procedure with the same name as a restricted keyword. Square
brackets can also be used to force Visual Basic to accept names provided by other type libraries that conflict with restricted keywords.

Note Because typing square brackets can get tedious, you might want to refrain from using restricted keywords as the name of forms and controls. However, you can use this technique if a
future version of Visual Basic defines a new keyword that conflicts with an existing form or control name when you update your code to work with the new version.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcodebasics.asp (3 of 3) [11/17/2002 10:43:32 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals

MSDN Library GO
Advanced Search Visual Basic Concepts

Introduction to Procedures

See Also

Up One Level You can simplify programming tasks by breaking programs into smaller logical components. These components — called procedures — can then become building blocks that let you enhance and
extend Visual Basic.
Sub Procedures
Function Procedures Procedures are useful for condensing repeated or shared tasks, such as frequently used calculations, text and control manipulation, and database operations.
Working with Procedures
Passing Arguments to Procedures There are two major benefits of programming with procedures:

● Procedures allow you to break your programs into discrete logical units, each of which you can debug more easily than an entire program without procedures.

● Procedures used in one program can act as building blocks for other programs, usually with little or no modification.

There are several types of procedures used in Visual Basic:

● Sub procedures do not return a value.

● Function procedures return a value.

● Property procedures can return and assign values, and set references to objects.

For More Information Property procedures are discussed in "Programming with Objects."

To learn more about Sub and Function procedures, see the following topics:

● Sub Procedures A discussion of Sub procedures and how to use them.


● Function Procedures An introduction to Function procedures and how to use them.
● Working with Procedures An introduction to calling procedures from within an application.
● Passing Arguments to Procedures A discussion of passing data to procedures using arguments.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconintroductiontoprocedures.asp [11/17/2002 10:48:18 PM]


Sub Procedures

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Procedures

Visual Basic Concepts

Sub Procedures

See Also

A Sub procedure is a block of code that is executed in response to an event. By breaking the code in a module into Sub procedures, it becomes much easier to find or modify the code in your
application.

The syntax for a Sub procedure is:

[Private|Public][Static]Sub procedurename (arguments)


statements

End Sub

Each time the procedure is called, the statements between Sub and End Sub are executed. Sub procedures can be placed in standard modules, class modules, and form modules. Sub procedures
are by default Public in all modules, which means they can be called from anywhere in the application.

The arguments for a procedure are like a variable declaration, declaring values that are passed in from the calling procedure.

In Visual Basic, it's useful to distinguish between two types of Sub procedures, general procedures and event procedures.

General Procedures

A general procedure tells the application how to perform a specific task. Once a general procedure is defined, it must be specifically invoked by the application. By contrast, an event procedure
remains idle until called upon to respond to events caused by the user or triggered by the system.

Why create general procedures? One reason is that several different event procedures might need the same actions performed. A good programming strategy is to put common statements in a
separate procedure (a general procedure) and have your event procedures call it. This eliminates the need to duplicate code and also makes the application easier to maintain. For example, the
VCR sample application uses a general procedure called by the click events for several different scroll buttons. Figure 5.7 illustrates the use of a general procedure. Code in the Click events calls
the ButtonManager Sub procedure, which runs its own code, and then returns control to the Click event procedure.

Figure 5.7 How general procedures are called by event procedures

Event Procedures

When an object in Visual Basic recognizes that an event has occurred, it automatically invokes the event procedure using the name corresponding to the event. Because the name establishes an
association between the object and the code, event procedures are said to be attached to forms and controls.

● An event procedure for a control combines the control's actual name (specified in the Name property), an underscore (_), and the event name. For instance, if you want a command button named cmdPlay to invoke an event procedure when it is clicked, use the
procedure cmdPlay_Click.

● An event procedure for a form combines the word "Form," an underscore, and the event name. If you want a form to invoke an event procedure when it is clicked, use the procedure Form_Click. (Like controls, forms do have unique names, but they are not used in
the names of event procedures.) If you are using the MDI form, the event procedure combines the word "MDIForm," an underscore, and the event name, as in MDIForm_Load.

All event procedures use the same general syntax.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconsubprocedures.asp?frame=true (1 of 2) [11/17/2002 10:48:21 PM]


Sub Procedures

Syntax for a control event Syntax for a form event

Private Sub controlname_eventname (arguments ) Private Sub Form_eventname (arguments)


statements statements
End Sub

End Sub

Although you can write event procedures from scratch, it's easier to use the code procedures provided by Visual Basic, which automatically include the correct procedure names. You can select a
template in the Code Editor window by selecting an object from the Object box and then selecting a procedure from the Procedure box.

It's also a good idea to set the Name property of your controls before you start writing event procedures for them. If you change the name of a control after attaching a procedure to it, you must
also change the name of the procedure to match the new name of the control. Otherwise, Visual Basic won't be able to match the control to the procedure. When a procedure name does not match
a control name, it becomes a general procedure.

For More Information Visual Basic recognizes a variety of events for each kind of form and control. For explanations of all events, see the Language Reference.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconsubprocedures.asp?frame=true (2 of 2) [11/17/2002 10:48:21 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Procedures

MSDN Library GO
Advanced Search Visual Basic Concepts

Sub Procedures

See Also

Up One Level A Sub procedure is a block of code that is executed in response to an event. By breaking the code in a module into Sub procedures, it becomes much easier to find or modify the code in your
application.
Sub Procedures
Function Procedures The syntax for a Sub procedure is:
Working with Procedures
Passing Arguments to Procedures [Private|Public][Static]Sub procedurename (arguments)
statements

End Sub

Each time the procedure is called, the statements between Sub and End Sub are executed. Sub procedures can be placed in standard modules, class modules, and form modules. Sub
procedures are by default Public in all modules, which means they can be called from anywhere in the application.

The arguments for a procedure are like a variable declaration, declaring values that are passed in from the calling procedure.

In Visual Basic, it's useful to distinguish between two types of Sub procedures, general procedures and event procedures.

General Procedures

A general procedure tells the application how to perform a specific task. Once a general procedure is defined, it must be specifically invoked by the application. By contrast, an event procedure
remains idle until called upon to respond to events caused by the user or triggered by the system.

Why create general procedures? One reason is that several different event procedures might need the same actions performed. A good programming strategy is to put common statements in a
separate procedure (a general procedure) and have your event procedures call it. This eliminates the need to duplicate code and also makes the application easier to maintain. For example, the
VCR sample application uses a general procedure called by the click events for several different scroll buttons. Figure 5.7 illustrates the use of a general procedure. Code in the Click events calls
the ButtonManager Sub procedure, which runs its own code, and then returns control to the Click event procedure.

Figure 5.7 How general procedures are called by event procedures

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconsubprocedures.asp (1 of 2) [11/17/2002 10:48:23 PM]


Welcome to the MSDN Library

Event Procedures

When an object in Visual Basic recognizes that an event has occurred, it automatically invokes the event procedure using the name corresponding to the event. Because the name establishes
an association between the object and the code, event procedures are said to be attached to forms and controls.

● An event procedure for a control combines the control's actual name (specified in the Name property), an underscore (_), and the event name. For instance, if you want a command button named cmdPlay to invoke an event procedure when it is clicked, use
the procedure cmdPlay_Click.

● An event procedure for a form combines the word "Form," an underscore, and the event name. If you want a form to invoke an event procedure when it is clicked, use the procedure Form_Click. (Like controls, forms do have unique names, but they are not
used in the names of event procedures.) If you are using the MDI form, the event procedure combines the word "MDIForm," an underscore, and the event name, as in MDIForm_Load.

All event procedures use the same general syntax.

Syntax for a control event Syntax for a form event

Private Sub controlname_eventname (arguments ) Private Sub Form_eventname (arguments)


statements statements
End Sub

End Sub

Although you can write event procedures from scratch, it's easier to use the code procedures provided by Visual Basic, which automatically include the correct procedure names. You can select
a template in the Code Editor window by selecting an object from the Object box and then selecting a procedure from the Procedure box.

It's also a good idea to set the Name property of your controls before you start writing event procedures for them. If you change the name of a control after attaching a procedure to it, you
must also change the name of the procedure to match the new name of the control. Otherwise, Visual Basic won't be able to match the control to the procedure. When a procedure name does
not match a control name, it becomes a general procedure.

For More Information Visual Basic recognizes a variety of events for each kind of form and control. For explanations of all events, see the Language Reference.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconsubprocedures.asp (2 of 2) [11/17/2002 10:48:23 PM]


Function Procedures

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Procedures

Visual Basic Concepts

Function Procedures

See Also

Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr. In addition, you can use the Function statement to write your own Function procedures.

The syntax for a Function procedure is:

[Private|Public][Static]Function procedurename (arguments) [As type]


statements

End Function

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. Unlike a Sub procedure, a
Function procedure can return a value to the calling procedure. There are three differences between Sub and Function procedures:

● Generally, you call a function by including the function procedure name and arguments on the right side of a larger statement or expression (returnvalue = function()).

● Function procedures have data types, just as variables do. This determines the type of the return value. (In the absence of an As clause, the type is the default Variant type.)

● You return a value by assigning it to the procedurename itself. When the Function procedure returns a value, this value can then become part of a larger expression.

For example, you could write a function that calculates the third side, or hypotenuse, of a right triangle, given the values for the other two sides:

Function Hypotenuse (A As Integer, B As Integer) _


As String
Hypotenuse = Sqr(A ^ 2 + B ^ 2)
End Function

You call a Function procedure the same way you call any of the built-in functions in Visual Basic:

Label1.Caption = Hypotenuse(CInt(Text1.Text), _
CInt(Text2.Text))
strX = Hypotenuse(Width, Height)

For More Information For additional details about the Function procedure, see "Function Statement" in the Language Reference. The techniques for calling all types of procedures are discussed
in the section, "Calling Procedures," later in this chapter.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconfunctionprocedures.asp?frame=true [11/17/2002 10:48:31 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Procedures

MSDN Library GO
Advanced Search Visual Basic Concepts

Function Procedures

See Also

Up One Level Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr. In addition, you can use the Function statement to write your own Function procedures.

Sub Procedures
Function Procedures The syntax for a Function procedure is:

Working with Procedures


Passing Arguments to Procedures [Private|Public][Static]Function procedurename (arguments) [As type]
statements

End Function

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. Unlike a Sub procedure, a
Function procedure can return a value to the calling procedure. There are three differences between Sub and Function procedures:

● Generally, you call a function by including the function procedure name and arguments on the right side of a larger statement or expression (returnvalue = function()).

● Function procedures have data types, just as variables do. This determines the type of the return value. (In the absence of an As clause, the type is the default Variant type.)

● You return a value by assigning it to the procedurename itself. When the Function procedure returns a value, this value can then become part of a larger expression.

For example, you could write a function that calculates the third side, or hypotenuse, of a right triangle, given the values for the other two sides:

Function Hypotenuse (A As Integer, B As Integer) _


As String
Hypotenuse = Sqr(A ^ 2 + B ^ 2)
End Function

You call a Function procedure the same way you call any of the built-in functions in Visual Basic:

Label1.Caption = Hypotenuse(CInt(Text1.Text), _
CInt(Text2.Text))
strX = Hypotenuse(Width, Height)

For More Information For additional details about the Function procedure, see "Function Statement" in the Language Reference. The techniques for calling all types of procedures are
discussed in the section, "Calling Procedures," later in this chapter.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconfunctionprocedures.asp (1 of 2) [11/17/2002 10:48:32 PM]


Welcome to the MSDN Library

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconfunctionprocedures.asp (2 of 2) [11/17/2002 10:48:32 PM]


Working with Procedures

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Procedures

Visual Basic Concepts

Working with Procedures

See Also

Creating New Procedures

To create a new general procedure

● Type a procedure heading in the Code window and press ENTER. The procedure heading can be as simple as Sub or Function followed by a name. For example, you can enter either of the following:

Sub UpdateForm ()
Function GetCoord ()

Visual Basic responds by completing the template for the new procedure.

Selecting Existing Procedures

To view a procedure in the current module

● To view an existing general procedure, select "(General)" from the Object box in the Code window, and then select the procedure in the Procedure box.

–or–

To view an event procedure, select the appropriate object from the Object box in the Code window, and then select the event in the Procedure box.

To view a procedure in another module

1. From the View menu, choose Object Browser.

2. Select the project from the Project/Library box.

3. Select the module from the Classes list, and the procedure from the Members of list.

4. Choose View Definition.

Calling Procedures

The techniques for calling procedures vary, depending on the type of procedure, where it's located, and how it's used in your application. The following sections describe how to call Sub and
Function procedures.

Calling Sub Procedures

A Sub procedure differs from a Function procedure in that a Sub procedure cannot be called by using its name within an expression. A call to a Sub is a stand-alone statement. Also, a Sub does
not return a value in its name as does a function. However, like a Function, a Sub can modify the values of any variables passed to it.

There are two ways to call a Sub procedure:

' Both of these statements call a Sub named MyProc.


Call MyProc (FirstArgument, SecondArgument)
MyProc FirstArgument, SecondArgument

Note that when you use the Call syntax, arguments must be enclosed in parentheses. If you omit the Call keyword, you must also omit the parentheses around the arguments.

Calling Function Procedures

Usually, you call a function procedure you've written yourself the same way you call an intrinsic Visual Basic function like Abs; that is, by using its name in an expression:

' All of the following statements would call a function


' named ToDec.
Print 10 * ToDec
X = ToDec
If ToDec = 10 Then Debug.Print "Out of Range"
X = AnotherFunction(10 * ToDec)

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconworkingwithprocedures.asp?frame=true (1 of 2) [11/17/2002 10:48:38 PM]


Working with Procedures

It's also possible to call a function just like you would call a Sub procedure. The following statements both call the same function:

Call Year(Now)
Year Now

When you call a function this way, Visual Basic throws away the return value.

Calling Procedures in Other Modules

Public procedures in other modules can be called from anywhere in the project. You might need to specify the module that contains the procedure you're calling. The techniques for doing this vary,
depending on whether the procedure is located in a form, class, or standard module.

Procedures in Forms
All calls from outside the form module must point to the form module containing the procedure. If a procedure named SomeSub is in a form module called Form1, then you can call the procedure
in Form1 by using this statement:

Call Form1.SomeSub(arguments)

Procedures in Class Modules


Like calling a procedure in a form, calling a procedure in a class module requires that the call to the procedure be qualified with a variable that points to an instance of the class. For example,
DemoClass is an instance of a class named Class1:

Dim DemoClass as New Class1


DemoClass.SomeSub

However, unlike a form, the class name cannot be used as the qualifier when referencing an instance of the class. The instance of the class must be first be declared as an object variable (in this
case, DemoClass) and referenced by the variable name.

For More Information You can find details on object variables and class modules in "Programming with Objects."

Procedures in Standard Modules


If a procedure name is unique, you don't need to include the module name in the call. A call from inside or outside the module will refer to that unique procedure. A procedure is unique if it
appears only in one place.

If two or more modules contain a procedure with the same name, you may need to qualify it with the module name. A call to a common procedure from the same module runs the procedure in
that module. For example, with a procedure named CommonName in Module1 and Module2, a call to CommonName from Module2 will run the CommonName procedure in Module2, not the
CommonName procedure in Module1.

A call to a common procedure name from another module must specify the intended module. For example, if you want to call the CommonName procedure in Module2 from Module1, use:

Module2.CommonName(arguments)

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconworkingwithprocedures.asp?frame=true (2 of 2) [11/17/2002 10:48:38 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Procedures

MSDN Library GO
Advanced Search Visual Basic Concepts

Working with Procedures

See Also

Up One Level Creating New Procedures

Sub Procedures
To create a new general procedure
Function Procedures
Working with Procedures
● Type a procedure heading in the Code window and press ENTER. The procedure heading can be as simple as Sub or Function followed by a name. For example, you can enter either of the following:

Passing Arguments to Procedures


Sub UpdateForm ()
Function GetCoord ()

Visual Basic responds by completing the template for the new procedure.

Selecting Existing Procedures

To view a procedure in the current module

● To view an existing general procedure, select "(General)" from the Object box in the Code window, and then select the procedure in the Procedure box.

–or–

To view an event procedure, select the appropriate object from the Object box in the Code window, and then select the event in the Procedure box.

To view a procedure in another module

1. From the View menu, choose Object Browser.

2. Select the project from the Project/Library box.

3. Select the module from the Classes list, and the procedure from the Members of list.

4. Choose View Definition.

Calling Procedures

The techniques for calling procedures vary, depending on the type of procedure, where it's located, and how it's used in your application. The following sections describe how to call Sub and
Function procedures.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconworkingwithprocedures.asp (1 of 3) [11/17/2002 10:48:39 PM]


Welcome to the MSDN Library
Calling Sub Procedures

A Sub procedure differs from a Function procedure in that a Sub procedure cannot be called by using its name within an expression. A call to a Sub is a stand-alone statement. Also, a Sub does
not return a value in its name as does a function. However, like a Function, a Sub can modify the values of any variables passed to it.

There are two ways to call a Sub procedure:

' Both of these statements call a Sub named MyProc.


Call MyProc (FirstArgument, SecondArgument)
MyProc FirstArgument, SecondArgument

Note that when you use the Call syntax, arguments must be enclosed in parentheses. If you omit the Call keyword, you must also omit the parentheses around the arguments.

Calling Function Procedures

Usually, you call a function procedure you've written yourself the same way you call an intrinsic Visual Basic function like Abs; that is, by using its name in an expression:

' All of the following statements would call a function


' named ToDec.
Print 10 * ToDec
X = ToDec
If ToDec = 10 Then Debug.Print "Out of Range"
X = AnotherFunction(10 * ToDec)

It's also possible to call a function just like you would call a Sub procedure. The following statements both call the same function:

Call Year(Now)
Year Now

When you call a function this way, Visual Basic throws away the return value.

Calling Procedures in Other Modules

Public procedures in other modules can be called from anywhere in the project. You might need to specify the module that contains the procedure you're calling. The techniques for doing this
vary, depending on whether the procedure is located in a form, class, or standard module.

Procedures in Forms
All calls from outside the form module must point to the form module containing the procedure. If a procedure named SomeSub is in a form module called Form1, then you can call the
procedure in Form1 by using this statement:

Call Form1.SomeSub(arguments)

Procedures in Class Modules


Like calling a procedure in a form, calling a procedure in a class module requires that the call to the procedure be qualified with a variable that points to an instance of the class. For example,
DemoClass is an instance of a class named Class1:

Dim DemoClass as New Class1


DemoClass.SomeSub

However, unlike a form, the class name cannot be used as the qualifier when referencing an instance of the class. The instance of the class must be first be declared as an object variable (in
this case, DemoClass) and referenced by the variable name.

For More Information You can find details on object variables and class modules in "Programming with Objects."

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconworkingwithprocedures.asp (2 of 3) [11/17/2002 10:48:39 PM]


Welcome to the MSDN Library

Procedures in Standard Modules


If a procedure name is unique, you don't need to include the module name in the call. A call from inside or outside the module will refer to that unique procedure. A procedure is unique if it
appears only in one place.

If two or more modules contain a procedure with the same name, you may need to qualify it with the module name. A call to a common procedure from the same module runs the procedure in
that module. For example, with a procedure named CommonName in Module1 and Module2, a call to CommonName from Module2 will run the CommonName procedure in Module2, not the
CommonName procedure in Module1.

A call to a common procedure name from another module must specify the intended module. For example, if you want to call the CommonName procedure in Module2 from Module1, use:

Module2.CommonName(arguments)

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconworkingwithprocedures.asp (3 of 3) [11/17/2002 10:48:39 PM]


Passing Arguments to Procedures

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Procedures

Visual Basic Concepts

Passing Arguments to Procedures

See Also

Usually the code in a procedure needs some information about the state of the program to do its job. This information consists of variables passed to the procedure when it is called. When a
variable is passed to a procedure, it is called an argument.

Argument Data Types

The arguments for procedures you write have the Variant data type by default. However, you can declare other data types for arguments. For example, the following function accepts a string and
an integer:

Function WhatsForLunch(WeekDay As String, Hour _


As Integer) As String
' Returns a lunch menu based on the day and time.
If WeekDay = "Friday" then
WhatsForLunch = "Fish"
Else
WhatsForLunch = "Chicken"
End If
If Hour > 4 Then WhatsForLunch = "Too late"
End Function

For More Information Details on Visual Basic data types are presented earlier in this chapter. You can also see the Language Reference for specific data types.

Passing Arguments By Value

Only a copy of a variable is passed when an argument is passed by value. If the procedure changes the value, the change affects only the copy and not the variable itself. Use the ByVal keyword
to indicate an argument passed by value.

For example:

Sub PostAccounts(ByVal intAcctNum as Integer)


.
. ' Place statements here.
.
End Sub

Passing Arguments By Reference

Passing arguments by reference gives the procedure access to the actual variable contents in its memory address location. As a result, the variable's value can be permanently changed by the
procedure to which it is passed. Passing by reference is the default in Visual Basic.

If you specify a data type for an argument passed by reference, you must pass a value of that type for the argument. You can work around this by passing an expression, rather than a data type,
for an argument. Visual Basic evaluates an expression and passes it as the required type if it can.

The simplest way to turn a variable into an expression is to enclose it in parentheses. For example, to pass a variable declared as an integer to a procedure expecting a string as an argument, you
would do the following:

Sub CallingProcedure()
Dim intX As Integer
intX = 12 * 3
Foo(intX)
End Sub

Sub Foo(Bar As String)


MsgBox Bar 'The value of Bar is the string "36".
End Sub

Using Optional Arguments

You can specify arguments to a procedure as optional by placing the Optional keyword in the argument list. If you specify an optional argument, all subsequent arguments in the argument list
must also be optional and declared with the Optional keyword. The two pieces of sample code below assume there is a form with a command button and list box.

For example, this code provides all optional arguments:

http://msdn.microsoft.com/library/en-us/vbcon98/...vbconpassingargumentstoprocedures.asp?frame=true (1 of 3) [11/17/2002 10:48:55 PM]


Passing Arguments to Procedures

Dim strName As String


Dim strAddress As String

Sub ListText(Optional x As String, Optional y _


As String)
List1.AddItem x
List1.AddItem y
End Sub

Private Sub Command1_Click()


strName = "yourname"
strAddress = 12345 ' Both arguments are provided.
Call ListText(strName, strAddress)
End Sub

This code, however, does not provide all optional arguments:

Dim strName As String


Dim varAddress As Variant

Sub ListText(x As String, Optional y As Variant)


List1.AddItem x
If Not IsMissing(y) Then
List1.AddItem y
End If
End Sub

Private Sub Command1_Click()


strName = "yourname" ' Second argument is not
' provided.
Call ListText(strName)
End Sub

In the case where an optional argument is not provided, the argument is actually assigned as a variant with the value of Empty. The example above shows how to test for missing optional
arguments using the IsMissing function.

Providing a Default for an Optional Argument

It's also possible to specify a default value for an optional argument. The following example returns a default value if the optional argument isn't passed to the function procedure:

Sub ListText(x As String, Optional y As _


Integer = 12345)
List1.AddItem x
List1.AddItem y
End Sub

Private Sub Command1_Click()


strName = "yourname" ' Second argument is not
' provided.
Call ListText(strName) ' Adds "yourname" and
' "12345".
End Sub

Using an Indefinite Number of Arguments

Generally, the number of arguments in the procedure call must be the same as in the procedure specification. Using the ParamArray keyword allows you to specify that a procedure will accept an
arbitrary number of arguments. This allows you to write functions like Sum:

Dim x As Integer
Dim y As Integer
Dim intSum As Integer

Sub Sum(ParamArray intNums())


For Each x In intNums
y = y + x
Next x
intSum = y
End Sub

Private Sub Command1_Click()


Sum 1, 3, 5, 7, 8
List1.AddItem intSum
End Sub

Creating Simpler Statements with Named Arguments

For many built-in functions, statements, and methods, Visual Basic provides the option of using named arguments as a shortcut for typing argument values. With named arguments, you can
provide any or all of the arguments, in any order, by assigning a value to the named argument. You do this by typing the argument name plus a colon followed by an equal sign and the value (
MyArgument:= "SomeValue") and placing that assignment in any sequence delimited by commas. Notice that the arguments in the following example are in the reverse order of the expected
arguments:

Function ListText(strName As String, Optional strAddress As String)


List1.AddItem strName
List2.AddItem strAddress
End Sub

Private Sub Command1_Click()


ListText strAddress:="12345", strName:="Your Name"

http://msdn.microsoft.com/library/en-us/vbcon98/...vbconpassingargumentstoprocedures.asp?frame=true (2 of 3) [11/17/2002 10:48:55 PM]


Passing Arguments to Procedures
End Sub

This is especially useful if your procedures have several optional arguments that you do not always need to specify.

Determining Support for Named Arguments


To determine which functions, statements, and methods support named arguments, use the AutoQuickInfo feature in the Code window, check the Object Browser, or see the Language Reference.
Consider the following when working with named arguments:

● Named arguments are not supported by methods on objects in the Visual Basic (VB) object library. They are supported by all language keywords in the Visual Basic for applications (VBA) object library.

● In syntax, named arguments are shown as bold and italic. All other arguments are shown in italic only.

Important You cannot use named arguments to avoid entering required arguments. You can omit only the optional arguments. For Visual Basic (VB) and Visual Basic for applications (VBA)
object libraries, the Object Browser encloses optional arguments with square brackets [ ].

For More Information See "ByVal," "ByRef," "Optional," and "ParamArray" in the Language Reference.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/...vbconpassingargumentstoprocedures.asp?frame=true (3 of 3) [11/17/2002 10:48:55 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Procedures

MSDN Library GO
Advanced Search Visual Basic Concepts

Passing Arguments to Procedures

See Also

Up One Level Usually the code in a procedure needs some information about the state of the program to do its job. This information consists of variables passed to the procedure when it is called. When a
variable is passed to a procedure, it is called an argument.
Sub Procedures
Function Procedures Argument Data Types
Working with Procedures
Passing Arguments to Procedures The arguments for procedures you write have the Variant data type by default. However, you can declare other data types for arguments. For example, the following function accepts a string
and an integer:

Function WhatsForLunch(WeekDay As String, Hour _


As Integer) As String
' Returns a lunch menu based on the day and time.
If WeekDay = "Friday" then
WhatsForLunch = "Fish"
Else
WhatsForLunch = "Chicken"
End If
If Hour > 4 Then WhatsForLunch = "Too late"
End Function

For More Information Details on Visual Basic data types are presented earlier in this chapter. You can also see the Language Reference for specific data types.

Passing Arguments By Value

Only a copy of a variable is passed when an argument is passed by value. If the procedure changes the value, the change affects only the copy and not the variable itself. Use the ByVal
keyword to indicate an argument passed by value.

For example:

Sub PostAccounts(ByVal intAcctNum as Integer)


.
. ' Place statements here.
.
End Sub

Passing Arguments By Reference

Passing arguments by reference gives the procedure access to the actual variable contents in its memory address location. As a result, the variable's value can be permanently changed by the
procedure to which it is passed. Passing by reference is the default in Visual Basic.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconpassingargumentstoprocedures.asp (1 of 3) [11/17/2002 10:48:56 PM]


Welcome to the MSDN Library

If you specify a data type for an argument passed by reference, you must pass a value of that type for the argument. You can work around this by passing an expression, rather than a data
type, for an argument. Visual Basic evaluates an expression and passes it as the required type if it can.

The simplest way to turn a variable into an expression is to enclose it in parentheses. For example, to pass a variable declared as an integer to a procedure expecting a string as an argument,
you would do the following:

Sub CallingProcedure()
Dim intX As Integer
intX = 12 * 3
Foo(intX)
End Sub

Sub Foo(Bar As String)


MsgBox Bar 'The value of Bar is the string "36".
End Sub

Using Optional Arguments

You can specify arguments to a procedure as optional by placing the Optional keyword in the argument list. If you specify an optional argument, all subsequent arguments in the argument list
must also be optional and declared with the Optional keyword. The two pieces of sample code below assume there is a form with a command button and list box.

For example, this code provides all optional arguments:

Dim strName As String


Dim strAddress As String

Sub ListText(Optional x As String, Optional y _


As String)
List1.AddItem x
List1.AddItem y
End Sub

Private Sub Command1_Click()


strName = "yourname"
strAddress = 12345 ' Both arguments are provided.
Call ListText(strName, strAddress)
End Sub

This code, however, does not provide all optional arguments:

Dim strName As String


Dim varAddress As Variant

Sub ListText(x As String, Optional y As Variant)


List1.AddItem x
If Not IsMissing(y) Then
List1.AddItem y
End If
End Sub

Private Sub Command1_Click()


strName = "yourname" ' Second argument is not
' provided.
Call ListText(strName)
End Sub

In the case where an optional argument is not provided, the argument is actually assigned as a variant with the value of Empty. The example above shows how to test for missing optional
arguments using the IsMissing function.

Providing a Default for an Optional Argument

It's also possible to specify a default value for an optional argument. The following example returns a default value if the optional argument isn't passed to the function procedure:

Sub ListText(x As String, Optional y As _


Integer = 12345)
List1.AddItem x
List1.AddItem y
End Sub

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconpassingargumentstoprocedures.asp (2 of 3) [11/17/2002 10:48:56 PM]


Welcome to the MSDN Library
Private Sub Command1_Click()
strName = "yourname" ' Second argument is not
' provided.
Call ListText(strName) ' Adds "yourname" and
' "12345".
End Sub

Using an Indefinite Number of Arguments

Generally, the number of arguments in the procedure call must be the same as in the procedure specification. Using the ParamArray keyword allows you to specify that a procedure will accept
an arbitrary number of arguments. This allows you to write functions like Sum:

Dim x As Integer
Dim y As Integer
Dim intSum As Integer

Sub Sum(ParamArray intNums())


For Each x In intNums
y = y + x
Next x
intSum = y
End Sub

Private Sub Command1_Click()


Sum 1, 3, 5, 7, 8
List1.AddItem intSum
End Sub

Creating Simpler Statements with Named Arguments

For many built-in functions, statements, and methods, Visual Basic provides the option of using named arguments as a shortcut for typing argument values. With named arguments, you can
provide any or all of the arguments, in any order, by assigning a value to the named argument. You do this by typing the argument name plus a colon followed by an equal sign and the value (
MyArgument:= "SomeValue") and placing that assignment in any sequence delimited by commas. Notice that the arguments in the following example are in the reverse order of the expected
arguments:

Function ListText(strName As String, Optional strAddress As String)


List1.AddItem strName
List2.AddItem strAddress
End Sub

Private Sub Command1_Click()


ListText strAddress:="12345", strName:="Your Name"
End Sub

This is especially useful if your procedures have several optional arguments that you do not always need to specify.

Determining Support for Named Arguments


To determine which functions, statements, and methods support named arguments, use the AutoQuickInfo feature in the Code window, check the Object Browser, or see the Language
Reference. Consider the following when working with named arguments:

● Named arguments are not supported by methods on objects in the Visual Basic (VB) object library. They are supported by all language keywords in the Visual Basic for applications (VBA) object library.

● In syntax, named arguments are shown as bold and italic. All other arguments are shown in italic only.

Important You cannot use named arguments to avoid entering required arguments. You can omit only the optional arguments. For Visual Basic (VB) and Visual Basic for applications (VBA)
object libraries, the Object Browser encloses optional arguments with square brackets [ ].

For More Information See "ByVal," "ByRef," "Optional," and "ParamArray" in the Language Reference.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconpassingargumentstoprocedures.asp (3 of 3) [11/17/2002 10:48:56 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals

MSDN Library GO
Advanced Search Visual Basic Concepts

Introduction to Control Structures

See Also

Up One Level Control structures allow you to control the flow of your program's execution. If left unchecked by control-flow statements, a program's logic will flow through statements from left to right, and
top to bottom. While some very simple programs can be written with only this unidirectional flow, and while some flow can be controlled by using operators to regulate precedence of
Decision Structures operations, most of the power and utility of any programming language comes from its ability to change statement order with structures and loops.

Loop Structures
Working with Control Structures To learn more about specific control structures, see the following topics:

● Decision Structures An introduction to decision structures used for branching.


● Loop Structures An introduction to loop structures used to repeat processes.
● Working with Control Structures The basics of working with control structures in your code.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconintroductiontocontrolstructures.asp [11/17/2002 10:49:15 PM]


Decision Structures

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Control Structures

Visual Basic Concepts

Decision Structures

See Also

Visual Basic procedures can test conditions and then, depending on the results of that test, perform different operations. The decision structures that Visual Basic supports include:

● If...Then

● If...Then...Else

● Select Case

If...Then

Use an If...Then structure to execute one or more statements conditionally. You can use either a single-line syntax or a multiple-line block syntax:

If condition Then statement

If condition Then
statements

End If

The condition is usually a comparison, but it can be any expression that evaluates to a numeric value. Visual Basic interprets this value as True or False; a zero numeric value is False, and any
nonzero numeric value is considered True. If condition is True, Visual Basic executes all the statements following the Then keyword. You can use either single-line or multiple-line syntax to execute
just one statement conditionally (these two examples are equivalent):

If anyDate < Now Then anyDate = Now

If anyDate < Now Then


anyDate = Now
End If

Notice that the single-line form of If...Then does not use an End If statement. If you want to execute more than one line of code when condition is True, you must use the multiple-line block
If...Then...End If syntax.

If anyDate < Now Then


anyDate = Now
Timer1.Enabled = False ' Disable timer control.
End If

If...Then...Else

Use an If...Then...Else block to define several blocks of statements, one of which will execute:

If condition1 Then
[statementblock-1]
[ElseIf condition2 Then
[statementblock-2]] ...
[Else
[statementblock-n]]

End If

Visual Basic first tests condition1. If it's False, Visual Basic proceeds to test condition2, and so on, until it finds a True condition. When it finds a True condition, Visual Basic executes the
corresponding statement block and then executes the code following the End If. As an option, you can include an Else statement block, which Visual Basic executes if none of the conditions are
True.

If...Then…ElseIf is really just a special case of If...Then...Else. Notice that you can have any number of ElseIf clauses, or none at all. You can include an Else clause regardless of whether you have
ElseIf clauses.

For example, your application could perform different actions depending on which control in a menu control array was clicked:

Private Sub mnuCut_Click (Index As Integer)

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcondecisionstructures.asp?frame=true (1 of 2) [11/17/2002 10:49:17 PM]


Decision Structures
If Index = 0 Then ' Cut command.
CopyActiveControl ' Call general procedures.
ClearActiveControl
ElseIf Index = 1 Then ' Copy command.
CopyActiveControl
ElseIf Index = 2 Then ' Clear command.
ClearActiveControl
Else ' Paste command.
PasteActiveControl
End If
End Sub

Notice that you can always add more ElseIf parts to your If...Then structure. However, this syntax can get tedious to write when each ElseIf compares the same expression to a different value. For
this situation, you can use a Select Case decision structure.

For More Information See "If...Then...Else Statement" in the Language Reference.

Select Case

Visual Basic provides the Select Case structure as an alternative to If...Then...Else for selectively executing one block of statements from among multiple blocks of statements. A Select Case
statement provides capability similar to the If...Then...Else statement, but it makes code more readable when there are several choices.

A Select Case structure works with a single test expression that is evaluated once, at the top of the structure. Visual Basic then compares the result of this expression with the values for each Case
in the structure. If there is a match, it executes the block of statements associated with that Case:

Select Case testexpression


[Case expressionlist1
[statementblock-1]]
[Case expressionlist2
[statementblock-2]]
.
.
.
[Case Else
[statementblock-n]]

End Select

Each expressionlist is a list of one or more values. If there is more than one value in a single list, the values are separated by commas. Each statementblock contains zero or more statements. If
more than one Case matches the test expression, only the statement block associated with the first matching Case will execute. Visual Basic executes statements in the Case Else clause (which is
optional) if none of the values in the expression lists matches the test expression.

For example, suppose you added another command to the Edit menu in the If...Then...Else example. You could add another ElseIf clause, or you could write the function with Select Case:

Private Sub mnuCut_Click (Index As Integer)


Select Case Index
Case 0 ' Cut command.
CopyActiveControl ' Call general procedures.
ClearActiveControl
Case 1 ' Copy command.
CopyActiveControl
Case 2 ' Clear command.
ClearActiveControl
Case 3 ' Paste command.
PasteActiveControl
Case Else
frmFind.Show ' Show Find dialog box.
End Select
End Sub

Notice that the Select Case structure evaluates an expression once at the top of the structure. In contrast, the If...Then...Else structure can evaluate a different expression for each ElseIf
statement. You can replace an If...Then...Else structure with a Select Case structure only if the If statement and each ElseIf statement evaluates the same expression.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbcondecisionstructures.asp?frame=true (2 of 2) [11/17/2002 10:49:18 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Control Structures

MSDN Library GO
Advanced Search Visual Basic Concepts

Decision Structures

See Also

Up One Level Visual Basic procedures can test conditions and then, depending on the results of that test, perform different operations. The decision structures that Visual Basic supports include:

Decision Structures
Loop Structures ●


If...Then

If...Then...Else

Working with Control Structures ● Select Case

If...Then

Use an If...Then structure to execute one or more statements conditionally. You can use either a single-line syntax or a multiple-line block syntax:

If condition Then statement

If condition Then
statements

End If

The condition is usually a comparison, but it can be any expression that evaluates to a numeric value. Visual Basic interprets this value as True or False; a zero numeric value is False, and any
nonzero numeric value is considered True. If condition is True, Visual Basic executes all the statements following the Then keyword. You can use either single-line or multiple-line syntax to
execute just one statement conditionally (these two examples are equivalent):

If anyDate < Now Then anyDate = Now

If anyDate < Now Then


anyDate = Now
End If

Notice that the single-line form of If...Then does not use an End If statement. If you want to execute more than one line of code when condition is True, you must use the multiple-line block
If...Then...End If syntax.

If anyDate < Now Then


anyDate = Now
Timer1.Enabled = False ' Disable timer control.
End If

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondecisionstructures.asp (1 of 3) [11/17/2002 10:49:19 PM]


Welcome to the MSDN Library
If...Then...Else

Use an If...Then...Else block to define several blocks of statements, one of which will execute:

If condition1 Then
[statementblock-1]
[ElseIf condition2 Then
[statementblock-2]] ...
[Else
[statementblock-n]]

End If

Visual Basic first tests condition1. If it's False, Visual Basic proceeds to test condition2, and so on, until it finds a True condition. When it finds a True condition, Visual Basic executes the
corresponding statement block and then executes the code following the End If. As an option, you can include an Else statement block, which Visual Basic executes if none of the conditions are
True.

If...Then…ElseIf is really just a special case of If...Then...Else. Notice that you can have any number of ElseIf clauses, or none at all. You can include an Else clause regardless of whether you
have ElseIf clauses.

For example, your application could perform different actions depending on which control in a menu control array was clicked:

Private Sub mnuCut_Click (Index As Integer)


If Index = 0 Then ' Cut command.
CopyActiveControl ' Call general procedures.
ClearActiveControl
ElseIf Index = 1 Then ' Copy command.
CopyActiveControl
ElseIf Index = 2 Then ' Clear command.
ClearActiveControl
Else ' Paste command.
PasteActiveControl
End If
End Sub

Notice that you can always add more ElseIf parts to your If...Then structure. However, this syntax can get tedious to write when each ElseIf compares the same expression to a different value.
For this situation, you can use a Select Case decision structure.

For More Information See "If...Then...Else Statement" in the Language Reference.

Select Case

Visual Basic provides the Select Case structure as an alternative to If...Then...Else for selectively executing one block of statements from among multiple blocks of statements. A Select Case
statement provides capability similar to the If...Then...Else statement, but it makes code more readable when there are several choices.

A Select Case structure works with a single test expression that is evaluated once, at the top of the structure. Visual Basic then compares the result of this expression with the values for each
Case in the structure. If there is a match, it executes the block of statements associated with that Case:

Select Case testexpression


[Case expressionlist1
[statementblock-1]]
[Case expressionlist2
[statementblock-2]]
.
.
.
[Case Else
[statementblock-n]]

End Select

Each expressionlist is a list of one or more values. If there is more than one value in a single list, the values are separated by commas. Each statementblock contains zero or more statements.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondecisionstructures.asp (2 of 3) [11/17/2002 10:49:19 PM]


Welcome to the MSDN Library
If more than one Case matches the test expression, only the statement block associated with the first matching Case will execute. Visual Basic executes statements in the Case Else clause
(which is optional) if none of the values in the expression lists matches the test expression.

For example, suppose you added another command to the Edit menu in the If...Then...Else example. You could add another ElseIf clause, or you could write the function with Select Case:

Private Sub mnuCut_Click (Index As Integer)


Select Case Index
Case 0 ' Cut command.
CopyActiveControl ' Call general procedures.
ClearActiveControl
Case 1 ' Copy command.
CopyActiveControl
Case 2 ' Clear command.
ClearActiveControl
Case 3 ' Paste command.
PasteActiveControl
Case Else
frmFind.Show ' Show Find dialog box.
End Select
End Sub

Notice that the Select Case structure evaluates an expression once at the top of the structure. In contrast, the If...Then...Else structure can evaluate a different expression for each ElseIf
statement. You can replace an If...Then...Else structure with a Select Case structure only if the If statement and each ElseIf statement evaluates the same expression.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondecisionstructures.asp (3 of 3) [11/17/2002 10:49:19 PM]


Loop Structures

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Control Structures

Visual Basic Concepts

Loop Structures

See Also

Loop structures allow you to execute one or more lines of code repetitively. The loop structures that Visual Basic supports include:

● Do...Loop

● For...Next

● For Each...Next

Do...Loop

Use a Do loop to execute a block of statements an indefinite number of times. There are several variations of the Do...Loop statement, but each evaluates a numeric condition to determine
whether to continue execution. As with If...Then, the condition must be a value or expression that evaluates to False (zero) or to True (nonzero).

In the following Do...Loop, the statements execute as long as the condition is True:

Do While condition
statements

Loop

When Visual Basic executes this Do loop, it first tests condition. If condition is False (zero), it skips past all the statements. If it's True (nonzero), Visual Basic executes the statements and then
goes back to the Do While statement and tests the condition again.

Consequently, the loop can execute any number of times, as long as condition is nonzero or True. The statements never execute if condition is initially False. For example, this procedure counts
the occurrences of a target string within another string by looping as long as the target string is found:

Function CountStrings (longstring, target)


Dim position, count
position = 1
Do While InStr(position, longstring, target)
position = InStr(position, longstring, target)_
+ 1
count = count + 1
Loop
CountStrings = count
End Function

If the target string doesn't occur in the other string, then InStr returns 0, and the loop doesn't execute.

Another variation of the Do...Loop statement executes the statements first and then tests condition after each execution. This variation guarantees at least one execution of statements:

Do
statements

Loop While condition

Two other variations are analogous to the previous two, except that they loop as long as condition is False rather than True.

Loop zero or more times Loop at least once

Do Until condition Do
statements statements
Loop Loop Until condition

For...Next

Do loops work well when you don't know how many times you need to execute the statements in the loop. When you know you must execute the statements a specific number of times, however,
a For…Next loop is a better choice. Unlike a Do loop, a For loop uses a variable called a counter that increases or decreases in value during each repetition of the loop. The syntax is:

For counter = start To end [Step increment]

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconloopstructures.asp?frame=true (1 of 3) [11/17/2002 10:49:23 PM]


Loop Structures

statements

Next [counter]

The arguments counter, start, end, and increment are all numeric.

Note The increment argument can be either positive or negative. If increment is positive, start must be less than or equal to end or the statements in the loop will not execute. If increment is
negative, start must be greater than or equal to end for the body of the loop to execute. If Step isn't set, then increment defaults to 1.

In executing the For loop, Visual Basic:

1. Sets counter equal to start.

2. Tests to see if counter is greater than end. If so, Visual Basic exits the loop.

(If increment is negative, Visual Basic tests to see if counter is less than end.)

3. Executes the statements.

4. Increments counter by 1 or by increment, if it's specified.

5. Repeats steps 2 through 4.

This code prints the names of all the available Screen fonts:

Private Sub Form_Click ()


Dim I As Integer
For i = 0 To Screen.FontCount
Print Screen.Fonts(i)
Next
End Sub

In the VCR sample application, the HighlightButton procedure uses a For...Next loop to step through the controls collection of the VCR form and show the appropriate Shape control:

Sub HighlightButton(MyControl As Variant)


Dim i As Integer
For i = 0 To frmVCR.Controls.Count - 1
If TypeOf frmVCR.Controls(i) Is Shape Then
If frmVCR.Controls(i).Name = MyControl Then
frmVCR.Controls(i).Visible = True
Else
frmVCR.Controls(i).Visible = False
End If
End If
Next
End Sub

For Each...Next

A For Each...Next loop is similar to a For...Next loop, but it repeats a group of statements for each element in a collection of objects or in an array instead of repeating the statements a specified
number of times. This is especially helpful if you don't know how many elements are in a collection.

Here is the syntax for the For Each...Next loop:

For Each element In group


statements

Next element

For example, the following Sub procedure opens Biblio.mdb and adds the name of each table to a list box.

Sub ListTableDefs()
Dim objDb As Database
Dim MyTableDef as TableDef
Set objDb = OpenDatabase("c:\vb\biblio.mdb", _
True, False)
For Each MyTableDef In objDb.TableDefs()
List1.AddItem MyTableDef.Name
Next MyTableDef
End Sub

Keep the following restrictions in mind when using For Each...Next:

● For collections, element can only be a Variant variable, a generic Object variable, or an object listed in the Object Browser.

● For arrays, element can only be a Variant variable.

● You cannot use For Each...Next with an array of user-defined types because a Variant cannot contain a user-defined type.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconloopstructures.asp?frame=true (2 of 3) [11/17/2002 10:49:23 PM]


Loop Structures

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconloopstructures.asp?frame=true (3 of 3) [11/17/2002 10:49:23 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Control Structures

MSDN Library GO
Advanced Search Visual Basic Concepts

Loop Structures

See Also

Up One Level Loop structures allow you to execute one or more lines of code repetitively. The loop structures that Visual Basic supports include:

Decision Structures
Loop Structures ●


Do...Loop

For...Next

Working with Control Structures ● For Each...Next

Do...Loop

Use a Do loop to execute a block of statements an indefinite number of times. There are several variations of the Do...Loop statement, but each evaluates a numeric condition to determine
whether to continue execution. As with If...Then, the condition must be a value or expression that evaluates to False (zero) or to True (nonzero).

In the following Do...Loop, the statements execute as long as the condition is True:

Do While condition
statements

Loop

When Visual Basic executes this Do loop, it first tests condition. If condition is False (zero), it skips past all the statements. If it's True (nonzero), Visual Basic executes the statements and then
goes back to the Do While statement and tests the condition again.

Consequently, the loop can execute any number of times, as long as condition is nonzero or True. The statements never execute if condition is initially False. For example, this procedure counts
the occurrences of a target string within another string by looping as long as the target string is found:

Function CountStrings (longstring, target)


Dim position, count
position = 1
Do While InStr(position, longstring, target)
position = InStr(position, longstring, target)_
+ 1
count = count + 1
Loop
CountStrings = count
End Function

If the target string doesn't occur in the other string, then InStr returns 0, and the loop doesn't execute.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconloopstructures.asp (1 of 3) [11/17/2002 10:49:28 PM]


Welcome to the MSDN Library

Another variation of the Do...Loop statement executes the statements first and then tests condition after each execution. This variation guarantees at least one execution of statements:

Do
statements

Loop While condition

Two other variations are analogous to the previous two, except that they loop as long as condition is False rather than True.

Loop zero or more times Loop at least once

Do Until condition Do
statements statements
Loop Loop Until condition

For...Next

Do loops work well when you don't know how many times you need to execute the statements in the loop. When you know you must execute the statements a specific number of times,
however, a For…Next loop is a better choice. Unlike a Do loop, a For loop uses a variable called a counter that increases or decreases in value during each repetition of the loop. The syntax is:

For counter = start To end [Step increment]


statements

Next [counter]

The arguments counter, start, end, and increment are all numeric.

Note The increment argument can be either positive or negative. If increment is positive, start must be less than or equal to end or the statements in the loop will not execute. If increment is
negative, start must be greater than or equal to end for the body of the loop to execute. If Step isn't set, then increment defaults to 1.

In executing the For loop, Visual Basic:

1. Sets counter equal to start.

2. Tests to see if counter is greater than end. If so, Visual Basic exits the loop.

(If increment is negative, Visual Basic tests to see if counter is less than end.)

3. Executes the statements.

4. Increments counter by 1 or by increment, if it's specified.

5. Repeats steps 2 through 4.

This code prints the names of all the available Screen fonts:

Private Sub Form_Click ()


Dim I As Integer
For i = 0 To Screen.FontCount
Print Screen.Fonts(i)
Next
End Sub

In the VCR sample application, the HighlightButton procedure uses a For...Next loop to step through the controls collection of the VCR form and show the appropriate Shape control:

Sub HighlightButton(MyControl As Variant)


Dim i As Integer
For i = 0 To frmVCR.Controls.Count - 1
If TypeOf frmVCR.Controls(i) Is Shape Then
If frmVCR.Controls(i).Name = MyControl Then

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconloopstructures.asp (2 of 3) [11/17/2002 10:49:28 PM]


Welcome to the MSDN Library
frmVCR.Controls(i).Visible = True
Else
frmVCR.Controls(i).Visible = False
End If
End If
Next
End Sub

For Each...Next

A For Each...Next loop is similar to a For...Next loop, but it repeats a group of statements for each element in a collection of objects or in an array instead of repeating the statements a
specified number of times. This is especially helpful if you don't know how many elements are in a collection.

Here is the syntax for the For Each...Next loop:

For Each element In group


statements

Next element

For example, the following Sub procedure opens Biblio.mdb and adds the name of each table to a list box.

Sub ListTableDefs()
Dim objDb As Database
Dim MyTableDef as TableDef
Set objDb = OpenDatabase("c:\vb\biblio.mdb", _
True, False)
For Each MyTableDef In objDb.TableDefs()
List1.AddItem MyTableDef.Name
Next MyTableDef
End Sub

Keep the following restrictions in mind when using For Each...Next:

● For collections, element can only be a Variant variable, a generic Object variable, or an object listed in the Object Browser.

● For arrays, element can only be a Variant variable.

● You cannot use For Each...Next with an array of user-defined types because a Variant cannot contain a user-defined type.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconloopstructures.asp (3 of 3) [11/17/2002 10:49:28 PM]


Working with Control Structures

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Control Structures

Visual Basic Concepts

Working with Control Structures

See Also

Nested Control Structures

You can place control structures inside other control structures (such as an If...Then block within a For...Next loop). A control structure placed inside another control structure is said to be nested.

Control structures in Visual Basic can be nested to as many levels as you want. It's common practice to make nested decision structures and loop structures more readable by indenting the body
of the decision structure or loop.

For example, this procedure prints all the font names that are common to both the Printer and Screen:

Private Sub Form_Click()


Dim SFont, PFont
For Each SFont In Screen.Fonts()
For Each PFont In Printer.Fonts()
If SFont = PFont Then
Print SFont
End If
Next PFont
Next SFont
End Sub

Notice that the first Next closes the inner For loop and the last For closes the outer For loop. Likewise, in nested If statements, the End If statements automatically apply to the nearest prior If
statement. Nested Do...Loop structures work in a similar fashion, with the innermost Loop statement matching the innermost Do statement.

Exiting a Control Structure

The Exit statement allows you to exit directly from a For loop, Do loop, Sub procedure, or Function procedure. The syntax for the Exit statement is simple: Exit For can appear as many times as
needed inside a For loop, and Exit Do can appear as many times as needed inside a Do loop:

For counter = start To end [Step increment]


[statementblock]
[Exit For]
[statementblock]

Next [counter[, counter] [,...]]

Do [{While | Until} condition]


[statementblock]
[Exit Do]
[statementblock]

Loop

The Exit Do statement works with all versions of the Do loop syntax.

Exit For and Exit Do are useful because sometimes it's appropriate to quit a loop immediately, without performing any further iterations or statements within the loop. For example, in the previous
example that printed the fonts common to both the Screen and Printer, the code continues to compare Printer fonts against a given Screen font even when a match has already been found with an
earlier Printer font. A more efficient version of the function would exit the loop as soon as a match is found:

Private Sub Form_Click()


Dim SFont, PFont
For Each SFont In Screen.Fonts()
For Each PFont In Printer.Fonts()
If SFont = PFont Then
Print Sfont
Exit For ' Exit inner loop.
End If
Next PFont
Next SFont
End Sub

As this example illustrates, an Exit statement almost always appears inside an If statement or Select Case statement nested inside the loop.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconworkingwithcontrolstructures.asp?frame=true (1 of 2) [11/17/2002 10:49:34 PM]


Working with Control Structures

When you use an Exit statement to break out of a loop, the value of the counter variable differs, depending on how you leave the loop:

● When you complete a loop, the counter variable contains the value of the upper bound plus the step.

● When you exit a loop prematurely, the counter variable retains its value subject to the usual rules on scope.

● When you iterate off the end of a collection, the counter variable contains Nothing if it's an Object data type, and contains Empty if it's a Variant data type.

Exiting a Sub or Function Procedure

You can also exit a procedure from within a control structure. The syntax of Exit Sub and Exit Function is similar to that of Exit For and Exit Do in the previous section, "Exiting a Control Structure."
Exit Sub can appear as many times as needed, anywhere within the body of a Sub procedure. Exit Function can appear as many times as needed, anywhere within the body of a Function
procedure.

Exit Sub and Exit Function are useful when the procedure has done everything it needs to do and can return immediately. For example, if you want to change the previous example so it prints only
the first common Printer and Screen font it finds, you would use Exit Sub:

Private Sub Form_Click()


Dim SFont, PFont
For Each SFont In Screen.Fonts()
For Each PFont In Printer.Fonts()
If SFont = PFont Then
Print Sfont
Exit Sub ' Exit the procedure.
End If
Next PFont
Next SFont
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconworkingwithcontrolstructures.asp?frame=true (2 of 2) [11/17/2002 10:49:34 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Control Structures

MSDN Library GO
Advanced Search Visual Basic Concepts

Working with Control Structures

See Also

Up One Level Nested Control Structures

Decision Structures
You can place control structures inside other control structures (such as an If...Then block within a For...Next loop). A control structure placed inside another control structure is said to be
Loop Structures nested.

Working with Control Structures


Control structures in Visual Basic can be nested to as many levels as you want. It's common practice to make nested decision structures and loop structures more readable by indenting the
body of the decision structure or loop.

For example, this procedure prints all the font names that are common to both the Printer and Screen:

Private Sub Form_Click()


Dim SFont, PFont
For Each SFont In Screen.Fonts()
For Each PFont In Printer.Fonts()
If SFont = PFont Then
Print SFont
End If
Next PFont
Next SFont
End Sub

Notice that the first Next closes the inner For loop and the last For closes the outer For loop. Likewise, in nested If statements, the End If statements automatically apply to the nearest prior If
statement. Nested Do...Loop structures work in a similar fashion, with the innermost Loop statement matching the innermost Do statement.

Exiting a Control Structure

The Exit statement allows you to exit directly from a For loop, Do loop, Sub procedure, or Function procedure. The syntax for the Exit statement is simple: Exit For can appear as many times as
needed inside a For loop, and Exit Do can appear as many times as needed inside a Do loop:

For counter = start To end [Step increment]


[statementblock]
[Exit For]
[statementblock]

Next [counter[, counter] [,...]]

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconworkingwithcontrolstructures.asp (1 of 2) [11/17/2002 10:49:35 PM]


Welcome to the MSDN Library
Do [{While | Until} condition]
[statementblock]
[Exit Do]
[statementblock]

Loop

The Exit Do statement works with all versions of the Do loop syntax.

Exit For and Exit Do are useful because sometimes it's appropriate to quit a loop immediately, without performing any further iterations or statements within the loop. For example, in the
previous example that printed the fonts common to both the Screen and Printer, the code continues to compare Printer fonts against a given Screen font even when a match has already been
found with an earlier Printer font. A more efficient version of the function would exit the loop as soon as a match is found:

Private Sub Form_Click()


Dim SFont, PFont
For Each SFont In Screen.Fonts()
For Each PFont In Printer.Fonts()
If SFont = PFont Then
Print Sfont
Exit For ' Exit inner loop.
End If
Next PFont
Next SFont
End Sub

As this example illustrates, an Exit statement almost always appears inside an If statement or Select Case statement nested inside the loop.

When you use an Exit statement to break out of a loop, the value of the counter variable differs, depending on how you leave the loop:

● When you complete a loop, the counter variable contains the value of the upper bound plus the step.

● When you exit a loop prematurely, the counter variable retains its value subject to the usual rules on scope.

● When you iterate off the end of a collection, the counter variable contains Nothing if it's an Object data type, and contains Empty if it's a Variant data type.

Exiting a Sub or Function Procedure

You can also exit a procedure from within a control structure. The syntax of Exit Sub and Exit Function is similar to that of Exit For and Exit Do in the previous section, "Exiting a Control
Structure." Exit Sub can appear as many times as needed, anywhere within the body of a Sub procedure. Exit Function can appear as many times as needed, anywhere within the body of a
Function procedure.

Exit Sub and Exit Function are useful when the procedure has done everything it needs to do and can return immediately. For example, if you want to change the previous example so it prints
only the first common Printer and Screen font it finds, you would use Exit Sub:

Private Sub Form_Click()


Dim SFont, PFont
For Each SFont In Screen.Fonts()
For Each PFont In Printer.Fonts()
If SFont = PFont Then
Print Sfont
Exit Sub ' Exit the procedure.
End If
Next PFont
Next SFont
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconworkingwithcontrolstructures.asp (2 of 2) [11/17/2002 10:49:35 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals

MSDN Library GO
Advanced Search Visual Basic Concepts

Working with Objects

See Also

Up One Level When you create an application in Visual Basic, you work with objects. You can use objects provided by Visual Basic — such as controls, forms, and data access objects. You can also control
other applications' objects from within your Visual Basic application. You can even create your own objects, and define additional properties and methods for them.
What is an Object?
What Can You Do with Objects? The following topics discuss objects in detail:
The Basics of Working with Objects
How are Objects Related to Each Other? ● What is an Object? An introduction to the concept of objects.

Creating Objects ●


What Can You Do with Objects?
The Basics of Working with Objects
A discussion of some ways that objects can be used in an application.
An introduction to the properties and methods exposed by objects.
● How are Objects Related to Each Other? A discussion of object hierarchies, collections, and containers.
● Creating Objects A discussion of how objects can be created and used at run time.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconworkingwithobjects.asp [11/17/2002 10:49:58 PM]


What is an Object?

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects

Visual Basic Concepts

What is an Object?

See Also

An object is a combination of code and data that can be treated as a unit. An object can be a piece of an application, like a control or a form. An entire application can also be an object. The
following table describes examples of the types of objects you can use in Visual Basic.

Example Description

Command button Controls on a form, such as command buttons and frames, are objects.

Form Each form in a Visual Basic project is a separate object.

Database Databases are objects, and contain other objects, like fields and indexes.

Chart A chart in Microsoft Excel is an object.

Where do Objects Come From?

Each object in Visual Basic is defined by a class. To understand the relationship between an object and its class, think of cookie cutters and cookies. The cookie cutter is the class. It defines the
characteristics of each cookie — for instance, size and shape. The class is used to create objects. The objects are the cookies.

Two examples of the relationship between classes and objects in Visual Basic may make this clearer.

● The controls on the Toolbox in Visual Basic represent classes. The object known as a control doesn't exist until you draw it on a form. When you create a control, you're creating a copy or instance of the control class. That instance of the class is the object you
refer to in your application.

● The form you work with at design time is a class. At run time, Visual Basic creates an instance of the form's class.

The Properties window displays the class and Name property of objects in your Visual Basic application, as shown in Figure 5.8.

Figure 5.8 Object and class names shown in the Properties window

All objects are created as identical copies of their class. Once they exist as individual objects, their properties can be changed. For example, if you draw three command buttons on a form, each
command button object is an instance of the CommandButton class. Each object shares a common set of characteristics and capabilities (properties, methods, and events), defined by the class.
However, each has its own name, can be separately enabled and disabled, can be placed in a different location on the form, and so on.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconwhatisobject.asp?frame=true (1 of 2) [11/17/2002 10:50:07 PM]


What is an Object?

For simplicity, most of the material outside of this chapter won't make many references to an object's class. Just remember that the term "list box control," for example, means "an instance of the
ListBox class."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconwhatisobject.asp?frame=true (2 of 2) [11/17/2002 10:50:07 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects

MSDN Library GO
Advanced Search Visual Basic Concepts

What is an Object?

See Also

Up One Level An object is a combination of code and data that can be treated as a unit. An object can be a piece of an application, like a control or a form. An entire application can also be an object. The
following table describes examples of the types of objects you can use in Visual Basic.
What is an Object?
What Can You Do with Objects?
The Basics of Working with Objects Example Description

How are Objects Related to Each Other? Command button Controls on a form, such as command buttons and frames, are objects.

Creating Objects Form Each form in a Visual Basic project is a separate object.

Database Databases are objects, and contain other objects, like fields and indexes.

Chart A chart in Microsoft Excel is an object.

Where do Objects Come From?

Each object in Visual Basic is defined by a class. To understand the relationship between an object and its class, think of cookie cutters and cookies. The cookie cutter is the class. It defines the
characteristics of each cookie — for instance, size and shape. The class is used to create objects. The objects are the cookies.

Two examples of the relationship between classes and objects in Visual Basic may make this clearer.

● The controls on the Toolbox in Visual Basic represent classes. The object known as a control doesn't exist until you draw it on a form. When you create a control, you're creating a copy or instance of the control class. That instance of the class is the object
you refer to in your application.

● The form you work with at design time is a class. At run time, Visual Basic creates an instance of the form's class.

The Properties window displays the class and Name property of objects in your Visual Basic application, as shown in Figure 5.8.

Figure 5.8 Object and class names shown in the Properties window

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconwhatisobject.asp (1 of 2) [11/17/2002 10:50:09 PM]


Welcome to the MSDN Library

All objects are created as identical copies of their class. Once they exist as individual objects, their properties can be changed. For example, if you draw three command buttons on a form, each
command button object is an instance of the CommandButton class. Each object shares a common set of characteristics and capabilities (properties, methods, and events), defined by the
class. However, each has its own name, can be separately enabled and disabled, can be placed in a different location on the form, and so on.

For simplicity, most of the material outside of this chapter won't make many references to an object's class. Just remember that the term "list box control," for example, means "an instance of
the ListBox class."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconwhatisobject.asp (2 of 2) [11/17/2002 10:50:09 PM]


What Can You Do with Objects?

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects

Visual Basic Concepts

What Can You Do with Objects?

See Also

An object provides code you don't have to write. For example, you could create your own File Open and File Save dialog boxes, but you don't have to. Instead, you can use the common dialog
control (an object) provided by Visual Basic. You could write your own scheduling and resource management code, but you don't have to. Instead, you can use the Calendar, Resources, and Task
objects provided by Microsoft Project.

Visual Basic Can Combine Objects from Other Sources

Visual Basic provides the tools to allow you to combine objects from different sources. You can now build custom solutions combining the most powerful features of Visual Basic and applications
that support Automation (formerly known as OLE Automation). Automation is a feature of the Component Object Model (COM), an industry standard used by applications to expose objects to
development tools and other applications.

You can build applications by tying together intrinsic Visual Basic controls, and you can also use objects provided by other applications. Consider placing these objects on a Visual Basic form:

● A Microsoft Excel Chart object

● A Microsoft Excel Worksheet object

● A Microsoft Word Document object

You could use these objects to create a checkbook application like the one shown in Figure 5.9. This saves you time because you don't have to write the code to reproduce the functionality
provided by the Microsoft Excel and Word objects.

Figure 5.9 Using objects from other applications

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconwhatcanyoudowithobjects.asp?frame=true (1 of 2) [11/17/2002 10:50:15 PM]


What Can You Do with Objects?

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconwhatcanyoudowithobjects.asp?frame=true (2 of 2) [11/17/2002 10:50:15 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects

MSDN Library GO
Advanced Search Visual Basic Concepts

What Can You Do with Objects?

See Also

Up One Level An object provides code you don't have to write. For example, you could create your own File Open and File Save dialog boxes, but you don't have to. Instead, you can use the common dialog
control (an object) provided by Visual Basic. You could write your own scheduling and resource management code, but you don't have to. Instead, you can use the Calendar, Resources, and
What is an Object? Task objects provided by Microsoft Project.

What Can You Do with Objects?


The Basics of Working with Objects Visual Basic Can Combine Objects from Other Sources

How are Objects Related to Each Other?


Visual Basic provides the tools to allow you to combine objects from different sources. You can now build custom solutions combining the most powerful features of Visual Basic and applications
Creating Objects that support Automation (formerly known as OLE Automation). Automation is a feature of the Component Object Model (COM), an industry standard used by applications to expose objects to
development tools and other applications.

You can build applications by tying together intrinsic Visual Basic controls, and you can also use objects provided by other applications. Consider placing these objects on a Visual Basic form:

● A Microsoft Excel Chart object

● A Microsoft Excel Worksheet object

● A Microsoft Word Document object

You could use these objects to create a checkbook application like the one shown in Figure 5.9. This saves you time because you don't have to write the code to reproduce the functionality
provided by the Microsoft Excel and Word objects.

Figure 5.9 Using objects from other applications

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconwhatcanyoudowithobjects.asp (1 of 2) [11/17/2002 10:50:17 PM]


Welcome to the MSDN Library

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconwhatcanyoudowithobjects.asp (2 of 2) [11/17/2002 10:50:17 PM]


The Basics of Working with Objects

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects

Visual Basic Concepts

The Basics of Working with Objects

See Also

Visual Basic objects support properties, methods, and events. In Visual Basic, an object's data (settings or attributes) are called properties, while the various procedures that can operate on the
object are called its methods. An event is an action recognized by an object, such as clicking a mouse or pressing a key, and you can write code to respond to that event.

You can change an object's characteristics by changing its properties. Consider a radio: One property of a radio is its volume. In Visual Basic, you might say that a radio has a "Volume" property
that you can adjust by changing its value. Assume you can set the volume of the radio from 0 to 10. If you could control a radio with Visual Basic, you might write code in a procedure that
changes the value of the "Volume" property from 3 to 5 to make the radio play louder:

Radio.Volume = 5

In addition to properties, objects have methods. Methods are a part of objects just as properties are. Generally, methods are actions you want to perform, while properties are the attributes you
set or retrieve. For example, you dial a telephone to make a call. You might say that telephones have a "Dial" method, and you could use this syntax to dial the seven-digit number 5551111:

Phone.Dial 5551111

Objects also have events. Events are triggered when some aspect of the object is changed. For example, a radio might have a "VolumeChange" event. A telephone might have a "Ring" event.

Controlling Objects with Their Properties

Individual properties vary as to when you can set or get their values. Some properties can be set at design time. You can use the Properties window to set the value of these properties without
writing any code at all. Some properties are not available at design time; therefore, you must write code to set those properties at run time.

Properties that you can set and get at run time are called read-write properties. Properties you can only read at run time are called read-only properties.

Setting Property Values

You set the value of a property when you want to change the appearance or behavior of an object. For example, you change the Text property of a text box control to change the contents of the
text box.

To set the value of a property, use the following syntax:

object.property = expression

The following statements demonstrate how you set properties:

Text1.Top = 200 ' Sets the Top property to 200 twips.


Text1.Visible = True ' Displays the text box.
Text1.Text = "hello" ' Displays 'hello' in the text
' box.

Getting Property Values

You get the value of a property when you want to find the state of an object before your code performs additional actions (such as assigning the value to another object). For example, you can
return the Text property of a text box control to determine the contents of the text box before running code that might change the value.

In most cases, to get the value of a property, you use the following syntax:

variable = object.property

You can also get a property value as part of a more complex expression, without assigning the property to a variable. In the following code example, the Top property of the new member of a
control array is calculated as the Top property of the previous member, plus 400:

Private Sub cmdAdd_Click()


' [statements]
optButton(n).Top = optButton(n-1).Top + 400
' [statements]

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconthebasicsofworkingwithobjects.asp?frame=true (1 of 2) [11/17/2002 10:50:28 PM]


The Basics of Working with Objects
End Sub

Tip If you're going to use the value of a property more than once, your code will run faster if you store the value in a variable.

Performing Actions with Methods

Methods can affect the values of properties. For example, in the radio analogy, the SetVolume method changes the Volume property. Similarly, in Visual Basic, list boxes have a List property,
which can be changed with the Clear and AddItem methods.

Using Methods in Code

When you use a method in code, how you write the statement depends on how many arguments the method requires, and whether the method returns a value. When a method doesn't take
arguments, you write the code using the following syntax:

object.method

In this example, the Refresh method repaints the picture box:

Picture1.Refresh ' Forces a repaint of the control.

Some methods, such as the Refresh method, don't have arguments and don't return values.

If the method takes more than one argument, you separate the arguments with a comma. For example, the Circle method uses arguments specifying the location, radius, and color of a circle on a
form:

' Draw a blue circle with a 1200-twip radius.


Form1.Circle (1600, 1800), 1200, vbBlue

If you keep the return value of a method, you must enclose the arguments in parentheses. For example, the GetData method returns a picture from the Clipboard:

Picture = Clipboard.GetData (vbCFBitmap)

If there is no return value, the arguments appear without parentheses. For example, the AddItem method doesn't return a value:

List1.AddItem "yourname" ' Adds the text 'yourname'


' to a list box.

For More Information See the Language Reference for the syntax and arguments for all methods provided by Visual Basic.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconthebasicsofworkingwithobjects.asp?frame=true (2 of 2) [11/17/2002 10:50:28 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects

MSDN Library GO
Advanced Search Visual Basic Concepts

The Basics of Working with Objects

See Also

Up One Level Visual Basic objects support properties, methods, and events. In Visual Basic, an object's data (settings or attributes) are called properties, while the various procedures that can operate on the
object are called its methods. An event is an action recognized by an object, such as clicking a mouse or pressing a key, and you can write code to respond to that event.
What is an Object?
What Can You Do with Objects? You can change an object's characteristics by changing its properties. Consider a radio: One property of a radio is its volume. In Visual Basic, you might say that a radio has a "Volume"
The Basics of Working with Objects property that you can adjust by changing its value. Assume you can set the volume of the radio from 0 to 10. If you could control a radio with Visual Basic, you might write code in a procedure
that changes the value of the "Volume" property from 3 to 5 to make the radio play louder:
How are Objects Related to Each Other?
Creating Objects Radio.Volume = 5

In addition to properties, objects have methods. Methods are a part of objects just as properties are. Generally, methods are actions you want to perform, while properties are the attributes
you set or retrieve. For example, you dial a telephone to make a call. You might say that telephones have a "Dial" method, and you could use this syntax to dial the seven-digit number
5551111:

Phone.Dial 5551111

Objects also have events. Events are triggered when some aspect of the object is changed. For example, a radio might have a "VolumeChange" event. A telephone might have a "Ring" event.

Controlling Objects with Their Properties

Individual properties vary as to when you can set or get their values. Some properties can be set at design time. You can use the Properties window to set the value of these properties without
writing any code at all. Some properties are not available at design time; therefore, you must write code to set those properties at run time.

Properties that you can set and get at run time are called read-write properties. Properties you can only read at run time are called read-only properties.

Setting Property Values

You set the value of a property when you want to change the appearance or behavior of an object. For example, you change the Text property of a text box control to change the contents of
the text box.

To set the value of a property, use the following syntax:

object.property = expression

The following statements demonstrate how you set properties:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthebasicsofworkingwithobjects.asp (1 of 3) [11/17/2002 10:50:30 PM]


Welcome to the MSDN Library

Text1.Top = 200 ' Sets the Top property to 200 twips.


Text1.Visible = True ' Displays the text box.
Text1.Text = "hello" ' Displays 'hello' in the text
' box.

Getting Property Values

You get the value of a property when you want to find the state of an object before your code performs additional actions (such as assigning the value to another object). For example, you can
return the Text property of a text box control to determine the contents of the text box before running code that might change the value.

In most cases, to get the value of a property, you use the following syntax:

variable = object.property

You can also get a property value as part of a more complex expression, without assigning the property to a variable. In the following code example, the Top property of the new member of a
control array is calculated as the Top property of the previous member, plus 400:

Private Sub cmdAdd_Click()


' [statements]
optButton(n).Top = optButton(n-1).Top + 400
' [statements]
End Sub

Tip If you're going to use the value of a property more than once, your code will run faster if you store the value in a variable.

Performing Actions with Methods

Methods can affect the values of properties. For example, in the radio analogy, the SetVolume method changes the Volume property. Similarly, in Visual Basic, list boxes have a List property,
which can be changed with the Clear and AddItem methods.

Using Methods in Code

When you use a method in code, how you write the statement depends on how many arguments the method requires, and whether the method returns a value. When a method doesn't take
arguments, you write the code using the following syntax:

object.method

In this example, the Refresh method repaints the picture box:

Picture1.Refresh ' Forces a repaint of the control.

Some methods, such as the Refresh method, don't have arguments and don't return values.

If the method takes more than one argument, you separate the arguments with a comma. For example, the Circle method uses arguments specifying the location, radius, and color of a circle
on a form:

' Draw a blue circle with a 1200-twip radius.


Form1.Circle (1600, 1800), 1200, vbBlue

If you keep the return value of a method, you must enclose the arguments in parentheses. For example, the GetData method returns a picture from the Clipboard:

Picture = Clipboard.GetData (vbCFBitmap)

If there is no return value, the arguments appear without parentheses. For example, the AddItem method doesn't return a value:

List1.AddItem "yourname" ' Adds the text 'yourname'


' to a list box.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthebasicsofworkingwithobjects.asp (2 of 3) [11/17/2002 10:50:30 PM]


Welcome to the MSDN Library

For More Information See the Language Reference for the syntax and arguments for all methods provided by Visual Basic.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconthebasicsofworkingwithobjects.asp (3 of 3) [11/17/2002 10:50:30 PM]


How are Objects Related to Each Other?

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects

Visual Basic Concepts

How are Objects Related to Each Other?

See Also

When you put two command buttons on a form, they are separate objects with distinct Name property settings (Command1 and Command2), but they share the same class — CommandButton.

They also share the characteristic that they're on the same form. You've seen earlier in this chapter that a control on a form is also contained by the form. This puts controls in a hierarchy. To
reference a control you may have to reference the form first, in the same way you may have to dial a country code or area code before you can reach a particular phone number.

The two command buttons also share the characteristic that they're controls. All controls have common characteristics that make them different from forms and other objects in the Visual Basic
environment. The following sections explain how Visual Basic uses collections to group objects that are related.

Object Hierarchies

An object hierarchy provides the organization that determines how objects are related to each other, and how you can access them. In most cases, you don't need to concern yourself with the
Visual Basic object hierarchy. However:

● When manipulating another application's objects, you should be familiar with that application's object hierarchy. For information on navigating object hierarchies, see "Programming with Components."

● When working with data access objects, you should be familiar with the Data Access Object hierarchy.

There are some common cases in Visual Basic where one object contains others. These are described in the following sections.

Working with Collections of Objects

Collection objects have their own properties and methods. The objects in a collection object are referred to as members of the collection. Each member of the collection is numbered sequentially
beginning at 0; this is the member's index number. For example, the Controls collection contains all the controls on a given form, as shown in Figure 5.10. You can use collections to simplify code
if you need to perform the same operation on all the objects in a collection.

Figure 5.10 Controls collection

For example, the following code scrolls through the Controls collection and lists each member's name in a list box.

Dim MyControl as Control


For Each MyControl In Form1.Controls
' For each control, add its name to a list box.
List1.AddItem MyControl.Name
Next MyControl

Applying Properties and Methods to Collection Members

http://msdn.microsoft.com/library/en-us/vbcon98/h...conhowareobjectsrelatedtoeachother.asp?frame=true (1 of 3) [11/17/2002 10:51:44 PM]


How are Objects Related to Each Other?

There are two general techniques you can use to address a member of a collection object:

● Specify the name of the member. The following expressions are equivalent:

Controls("List1")
Controls!List1

● Use the index number of the member:

Controls(3)

Once you're able to address all the members collectively, and single members individually, you can apply properties and methods using either approach:

' Set the Top property of the list box control to 200.
Controls!List1.Top = 200

–or–

Dim MyControl as Control


For Each MyControl In Form1.Controls()
' Set the Top property of each member to 200.
MyControl.Top = 200
Next MyControl

Objects That Contain Other Objects

Some objects in Visual Basic contain other objects. For example, a form usually contains one or more controls. The advantage of having objects as containers for other objects is that you can refer
to the container in your code to make it clear which object you want to use. For example, Figure 5.11 illustrates two different forms you could have in an application — one for entering accounts
payable transactions, and the other for entering accounts receivable transactions.

Figure 5.11 Two different forms can contain controls that have the same name

Both forms can have a list box named lstAcctNo. You can specify exactly which one you want to use by referring to the form containing the list box:

frmReceivable.lstAcctNo.AddItem 1201

–or–

frmPayable.lstAcctNo.AddItem 1201

Common Collections in Visual Basic

There are some common cases in Visual Basic where one object contains other objects. The following table briefly describes the most commonly used collections in Visual Basic.

Collection Description

Forms Contains loaded forms.

http://msdn.microsoft.com/library/en-us/vbcon98/h...conhowareobjectsrelatedtoeachother.asp?frame=true (2 of 3) [11/17/2002 10:51:44 PM]


How are Objects Related to Each Other?

Controls Contains controls on a form.

Printers Contains the available Printer objects.

You can also implement object containment in Visual Basic.

For More Information "For information about object containment, see "Using Collections" in "More About Programming." For information on the Printers collection, see "Working with Text and
Graphics." For details on the forms and controls collections, see the Language Reference.

The Container Property

You can use the Container property to change an object's container within a form. The following controls can contain other controls:

● Frame control

● Picture box control

● Toolbar control (Professional and Enterprise editions only)

This example demonstrates moving a command button around from container to container on a form. Open a new project, and draw a frame control, picture box control and a command button on
the form.

The following code in the form's click event increments a counter variable, and uses a Select Case loop to rotate the command button from container to container.

Private Sub Form_Click()


Static intX as Integer
Select Case intX
Case 0
Set Command1.Container = Picture1
Command1.Top= 0
Command1.Left= 0

Case 1
Set Command1.Container = Frame1
Command1.Top= 0
Command1.Left= 0

Case 2
Set Command1.Container = Form1
Command1.Top= 0
Command1.Left= 0

End Select
intX = intX + 1
End Sub

For More Information See "Container Property" in the Language Reference.

Communicating Between Objects

In addition to using and creating objects within Visual Basic, you can communicate with other applications and manipulate their objects from within your application. The ability to share data
between applications is one of the key features of the Microsoft Windows operating system. With Visual Basic, you have great flexibility in how you can communicate with other applications.

For More Information For details on using and communicating with other applications' objects, see "Programming with Components."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/h...conhowareobjectsrelatedtoeachother.asp?frame=true (3 of 3) [11/17/2002 10:51:44 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects

MSDN Library GO
Advanced Search Visual Basic Concepts

How are Objects Related to Each Other?

See Also

Up One Level When you put two command buttons on a form, they are separate objects with distinct Name property settings (Command1 and Command2), but they share the same class —
CommandButton.
What is an Object?
What Can You Do with Objects? They also share the characteristic that they're on the same form. You've seen earlier in this chapter that a control on a form is also contained by the form. This puts controls in a hierarchy. To
The Basics of Working with Objects reference a control you may have to reference the form first, in the same way you may have to dial a country code or area code before you can reach a particular phone number.

How are Objects Related to Each Other?


Creating Objects The two command buttons also share the characteristic that they're controls. All controls have common characteristics that make them different from forms and other objects in the Visual Basic
environment. The following sections explain how Visual Basic uses collections to group objects that are related.

Object Hierarchies

An object hierarchy provides the organization that determines how objects are related to each other, and how you can access them. In most cases, you don't need to concern yourself with the
Visual Basic object hierarchy. However:

● When manipulating another application's objects, you should be familiar with that application's object hierarchy. For information on navigating object hierarchies, see "Programming with Components."

● When working with data access objects, you should be familiar with the Data Access Object hierarchy.

There are some common cases in Visual Basic where one object contains others. These are described in the following sections.

Working with Collections of Objects

Collection objects have their own properties and methods. The objects in a collection object are referred to as members of the collection. Each member of the collection is numbered
sequentially beginning at 0; this is the member's index number. For example, the Controls collection contains all the controls on a given form, as shown in Figure 5.10. You can use collections
to simplify code if you need to perform the same operation on all the objects in a collection.

Figure 5.10 Controls collection

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconhowareobjectsrelatedtoeachother.asp (1 of 4) [11/17/2002 10:51:46 PM]


Welcome to the MSDN Library

For example, the following code scrolls through the Controls collection and lists each member's name in a list box.

Dim MyControl as Control


For Each MyControl In Form1.Controls
' For each control, add its name to a list box.
List1.AddItem MyControl.Name
Next MyControl

Applying Properties and Methods to Collection Members


There are two general techniques you can use to address a member of a collection object:

● Specify the name of the member. The following expressions are equivalent:

Controls("List1")
Controls!List1

● Use the index number of the member:

Controls(3)

Once you're able to address all the members collectively, and single members individually, you can apply properties and methods using either approach:

' Set the Top property of the list box control to 200.
Controls!List1.Top = 200

–or–

Dim MyControl as Control


For Each MyControl In Form1.Controls()
' Set the Top property of each member to 200.
MyControl.Top = 200
Next MyControl

Objects That Contain Other Objects

Some objects in Visual Basic contain other objects. For example, a form usually contains one or more controls. The advantage of having objects as containers for other objects is that you can
refer to the container in your code to make it clear which object you want to use. For example, Figure 5.11 illustrates two different forms you could have in an application — one for entering
accounts payable transactions, and the other for entering accounts receivable transactions.

Figure 5.11 Two different forms can contain controls that have the same name

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconhowareobjectsrelatedtoeachother.asp (2 of 4) [11/17/2002 10:51:46 PM]


Welcome to the MSDN Library

Both forms can have a list box named lstAcctNo. You can specify exactly which one you want to use by referring to the form containing the list box:

frmReceivable.lstAcctNo.AddItem 1201

–or–

frmPayable.lstAcctNo.AddItem 1201

Common Collections in Visual Basic

There are some common cases in Visual Basic where one object contains other objects. The following table briefly describes the most commonly used collections in Visual Basic.

Collection Description

Forms Contains loaded forms.

Controls Contains controls on a form.

Printers Contains the available Printer objects.

You can also implement object containment in Visual Basic.

For More Information "For information about object containment, see "Using Collections" in "More About Programming." For information on the Printers collection, see "Working with Text
and Graphics." For details on the forms and controls collections, see the Language Reference.

The Container Property

You can use the Container property to change an object's container within a form. The following controls can contain other controls:

● Frame control

● Picture box control

● Toolbar control (Professional and Enterprise editions only)

This example demonstrates moving a command button around from container to container on a form. Open a new project, and draw a frame control, picture box control and a command button
on the form.

The following code in the form's click event increments a counter variable, and uses a Select Case loop to rotate the command button from container to container.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconhowareobjectsrelatedtoeachother.asp (3 of 4) [11/17/2002 10:51:46 PM]


Welcome to the MSDN Library
Private Sub Form_Click()
Static intX as Integer
Select Case intX
Case 0
Set Command1.Container = Picture1
Command1.Top= 0
Command1.Left= 0

Case 1
Set Command1.Container = Frame1
Command1.Top= 0
Command1.Left= 0

Case 2
Set Command1.Container = Form1
Command1.Top= 0
Command1.Left= 0

End Select
intX = intX + 1
End Sub

For More Information See "Container Property" in the Language Reference.

Communicating Between Objects

In addition to using and creating objects within Visual Basic, you can communicate with other applications and manipulate their objects from within your application. The ability to share data
between applications is one of the key features of the Microsoft Windows operating system. With Visual Basic, you have great flexibility in how you can communicate with other applications.

For More Information For details on using and communicating with other applications' objects, see "Programming with Components."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconhowareobjectsrelatedtoeachother.asp (4 of 4) [11/17/2002 10:51:46 PM]


Creating Objects

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects

Visual Basic Concepts

Creating Objects

See Also

The easiest way to create an object is to double-click a control in the Toolbox. However, to realize the full benefit of all the objects available in Visual Basic and from other applications, you can use
Visual Basic's programmability features to create objects at run time.

● You can create references to an object with object variables.

● You can create your own objects "from scratch" with class modules.

● You can create your own collections with the Collection object.

For More Information Other chapters show you how to access objects. The CreateObject and GetObject functions, for example, are discussed in "Programming with Components."

Using Object Variables

In addition to storing values, a variable can refer to an object. You assign an object to a variable for the same reasons you assign any value to a variable:

● Variable names are often shorter and easier to remember than the values they contain (or, in this case, the objects they refer to).

● Variables can be changed to refer to other objects while your code is running.

● Referring to a variable that contains an object is more efficient than repeatedly referring to the object itself.

Using an object variable is similar to using a conventional variable, but with one additional step — assigning an object to the variable:

● First you declare it:

Dim variable As class

● Then you assign an object to it:

Set variable = object

Declaring Object Variables

You declare an object variable in the same way you declare other variables, with Dim, ReDim, Static, Private, or Public. The only differences are the optional New keyword and the class argument;
both of these are discussed later in this chapter. The syntax is:

{Dim | ReDim | Static | Private | Public} variable As [New] class

For example, you can declare an object variable that refers to a form in the application called frmMain:

Dim FormVar As New frmMain ' Declare an object


' variable of type frmMain.

You can also declare an object variable that can refer to any form in the application:

Dim anyForm As Form ' Generic form variable.

Similarly, you can declare an object variable that can refer to any text box in your application:

Dim anyText As TextBox ' Can refer to any text box


' (but only a text box).

You can also declare an object variable that can refer to a control of any type:

Dim anyControl As Control ' Generic control variable.

Notice that you can declare a form variable that refers to a specific form in the application, but you cannot declare a control variable that refers to a particular control. You can declare a control
variable that can refer to a specific type of control (such as TextBox or ListBox), but not to one particular control of that type (such as txtEntry or List1). However, you can assign a particular
control to a variable of that type. For example, for a form with a list box called lstSample, you could write:

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconcreatingobjects.asp?frame=true (1 of 5) [11/17/2002 10:51:52 PM]


Creating Objects

Dim objDemo As ListBox


Set objDemo = lstSample

Assigning Object Variables

You assign an object to an object variable with the Set statement:

Set variable = object

Use the Set statement whenever you want an object variable to refer to an object.

Sometimes you may use object variables, and particularly control variables, simply to shorten the code you have to type. For example, you might write code like this:

If frmAccountDisplay!txtAccountBalance.Text < 0 Then


frmAccountDisplay!txtAccountBalance.BackColor = 0 frmAccountDisplay!txtAccountBalance.ForeColor = 255
End If

You can shorten this code significantly if you use a control variable:

Dim Bal As TextBox


Set Bal = frmAccountDisplay!txtAccountBalance
If Bal.Text < 0 Then
Bal.BackColor = 0
Bal.ForeColor = 255
End If

Specific and Generic Object Types

Specific object variables must refer to one specific type of object or class. A specific form variable can refer to only one form in the application (though it can refer to one of many instances of that
form). Similarly, a specific control variable can refer to only one particular type of control in your application, such as TextBox or ListBox. To see an example, open a new project and place a text
box on a form. Add the following code to the form:

Private Sub Form_Click()


Dim anyText As TextBox
Set anyText = Text1
anyText.Text = "Hello"
End Sub

Run the application, and click the form. The Text property of the text box will be changed to "Hello."

Generic object variables can refer to one of many specific types of objects. A generic form variable, for example, can refer to any form in an application; a generic control variable can refer to any
control on any form in an application. To see an example, open a new project and place several frame, label, and command button controls on a form, in any order. Add the following code to the
form:

Private Sub Form_Click()


Dim anyControl As Control
Set anyControl = Form1.Controls(3)
anyControl.Caption = "Hello"
End Sub

Run the application, and click the form. The caption of the control you placed third in sequence on the form will be changed to "Hello."

There are four generic object types in Visual Basic:

Generic Object
Type Object referenced

Form Any form in the application (including MDI children and the MDI form).

Control Any control in your application.

MDIForm The MDI form in the application (if your application has one).

Object Any object.

Generic object variables are useful when you don't know the specific type of object a variable will refer to at run time. For example, if you want to write code that can operate on any form in the
application, you must use a generic form variable.

Note Because there can be only one MDI form in the application, there is no need to use the generic MDIForm type. Instead, you can use the specific MDIForm type (MDIForm1, or whatever you

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconcreatingobjects.asp?frame=true (2 of 5) [11/17/2002 10:51:52 PM]


Creating Objects

specified for the Name property of the MDI form) whenever you need to declare a form variable that refers to the MDI form. In fact, because Visual Basic can resolve references to properties and
methods of specific form types before you run your application, you should always use the specific MDIForm type.

The generic MDIForm type is provided only for completeness; should a future version of Visual Basic allow multiple MDI forms in a single application, it might become useful.

Forms as Objects

Forms are most often used to make up the interface of an application, but they're also objects that can be called by other modules in your application. Forms are closely related to class modules.
The major difference between the two is that forms can be visible objects, whereas class modules have no visible interface.

Adding Custom Methods and Properties


You can add custom methods and properties to forms and access them from other modules in your application. To create a new method for a form, add a procedure declared using Public.

' Custom method on Form1


Public Sub LateJobsCount()
.
. ' <statements>
.
End Sub

You can call the LateJobsCount procedure from another module using this statement:

Form1.LateJobsCount

Creating a new property for a form can be as simple as declaring a public variable in the form module:

Public IDNumber As Integer

You can set and return the value of IDNumber on Form1 from another module using these two statements:

Form1.IDNumber = 3
Text1.Text = Form1.IDNumber

You can also use Property procedures to add custom properties to a form.

For More Information Details on Property procedures are provided in "Programming with Objects."

Note You can call a variable, a custom method, or set a custom property on a form without loading the form. This allows you to run code on a form without loading it into memory. Also,
referencing a control without referencing one of its properties or methods does not load the form.

Using the New Keyword

Use the New keyword to create a new object as defined by its class. New can be used to create instances of forms, classes defined in class modules, and collections.

Using the New Keyword with Forms


Each form you create at design time is a class. The New keyword can be used to create new instances of that class. To see how this works, draw a command button and several other controls on a
form. Set the form's Name property to Sample in the Properties window. Add the following code to your command button's Click event procedure:

Dim x As New Sample


x.Show

Run the application, and click the command button several times. Move the front-most form aside. Because a form is a class with a visible interface, you can see the additional copies. Each form
has the same controls, in the same positions as on the form at design time.

Note To make a form variable and an instance of the loaded form persist, use a Static or Public variable instead of a local variable.

You can also use New with the Set statement. Try the following code in a command button's Click event procedure:

Dim f As Form1
Set f = New Form1
f.Caption = "hello"

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconcreatingobjects.asp?frame=true (3 of 5) [11/17/2002 10:51:52 PM]


Creating Objects

f.Show

Using New with the Set statement is faster and is the recommended method.

Using the New Keyword with Other Objects


The New keyword can be used to create collections and objects from the classes you define in class modules. To see how this works, try the following example.

This example demonstrates how the New keyword creates instances of a class. Open a new project, and draw a command button on Form1. From the Project menu, choose Add Class Module to
add a class module to the project. Set the class module's Name property to ShowMe.

The following code in the Form1 module creates a new instance of the class ShowMe, and calls the procedure contained in the class module.

Public clsNew As ShowMe


Private Sub Command1_Click()
Set clsNew = New ShowMe
clsNew.ShowFrm
End Sub

The ShowFrm procedure in the class module creates a new instance of the class Form1, shows the form, and then minimizes it.

Sub ShowFrm()
Dim frmNew As Form1
Set frmNew = New Form1
frmNew.Show
frmNew.WindowState = 1
End Sub

To use the example, run the application, and click the command button several times. You'll see a minimized form icon appear on your desktop as each new instance of the ShowMe class is
created.

For More Information For information on using New to create objects, see "Programming with Components."

New Keyword Restrictions


The following table describes what you cannot do with the New keyword.

You can't use New to create Example of code not allowed

Variables of fundamental data types. Dim X As New Integer

A variable of any generic object type. Dim X As New Control

A variable of any specific control type. Dim X As New ListBox

A variable of any specific control. Dim X As New lstNames

Freeing References to Objects

Each object uses memory and system resources. It is good programming practice to release these resources when you are no longer using an object.

● Use Unload to unload a form or control from memory.

● Use Nothing to release resources used by an object variable. Assign Nothing to an object variable with the Set statement.

For More Information See "Unload Event" and "Nothing" in the Language Reference.

Passing Objects to Procedures

You can pass objects to procedures in Visual Basic. In the following code example, it's assumed that there is a command button on a form:

Private Sub Command1_Click()


' Calls the Demo sub, and passes the form to it.
Demo Form1
End Sub

Private Sub Demo(x As Form1)


' Centers the form on the screen.
x.Left = (Screen.Width - x.Width) / 2

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconcreatingobjects.asp?frame=true (4 of 5) [11/17/2002 10:51:52 PM]


Creating Objects
End Sub

It's also possible to pass an object to an argument by reference and then, inside the procedure, set the argument to a new object. To see how this works, open a project, and insert a second form.
Place a picture box control on each form. The following table shows the property settings that need changes:

Object Property Setting

Picture box on Form2 Name Picture2


Picture c:\vb\icons\arrows\arw01dn.ico

The Form1_Click event procedure calls the GetPicture procedure in Form2, and passes the empty picture box to it.

Private Sub Form_Click()


Form2.GetPicture Picture1
End Sub

The GetPicture procedure in Form2 assigns the Picture property of the picture box on Form2 to the empty picture box on Form1.

Private objX As PictureBox


Public Sub GetPicture(x As PictureBox)
' Assign the passed-in picture box to an object
' variable.
Set objX = x
' Assign the value of the Picture property to Form1
' picture box.
objX.Picture = picture2.Picture
End Sub

To use the example, run the application, and click Form1. You'll see the icon from Form2 appear in the picture box on Form1.

For More Information The previous topics are intended to serve as an introduction to objects. To learn more, see "Programming with Objects" and "Programming with Components."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconcreatingobjects.asp?frame=true (5 of 5) [11/17/2002 10:51:52 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating Objects

See Also

Up One Level The easiest way to create an object is to double-click a control in the Toolbox. However, to realize the full benefit of all the objects available in Visual Basic and from other applications, you can
use Visual Basic's programmability features to create objects at run time.
What is an Object?
What Can You Do with Objects? ● You can create references to an object with object variables.

The Basics of Working with Objects ● You can create your own objects "from scratch" with class modules.

You can create your own collections with the Collection object.
How are Objects Related to Each Other?

Creating Objects For More Information Other chapters show you how to access objects. The CreateObject and GetObject functions, for example, are discussed in "Programming with Components."

Using Object Variables

In addition to storing values, a variable can refer to an object. You assign an object to a variable for the same reasons you assign any value to a variable:

● Variable names are often shorter and easier to remember than the values they contain (or, in this case, the objects they refer to).

● Variables can be changed to refer to other objects while your code is running.

● Referring to a variable that contains an object is more efficient than repeatedly referring to the object itself.

Using an object variable is similar to using a conventional variable, but with one additional step — assigning an object to the variable:

● First you declare it:

Dim variable As class

● Then you assign an object to it:

Set variable = object

Declaring Object Variables

You declare an object variable in the same way you declare other variables, with Dim, ReDim, Static, Private, or Public. The only differences are the optional New keyword and the class
argument; both of these are discussed later in this chapter. The syntax is:

{Dim | ReDim | Static | Private | Public} variable As [New] class

For example, you can declare an object variable that refers to a form in the application called frmMain:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcreatingobjects.asp (1 of 6) [11/17/2002 10:51:54 PM]


Welcome to the MSDN Library
Dim FormVar As New frmMain ' Declare an object
' variable of type frmMain.

You can also declare an object variable that can refer to any form in the application:

Dim anyForm As Form ' Generic form variable.

Similarly, you can declare an object variable that can refer to any text box in your application:

Dim anyText As TextBox ' Can refer to any text box


' (but only a text box).

You can also declare an object variable that can refer to a control of any type:

Dim anyControl As Control ' Generic control variable.

Notice that you can declare a form variable that refers to a specific form in the application, but you cannot declare a control variable that refers to a particular control. You can declare a control
variable that can refer to a specific type of control (such as TextBox or ListBox), but not to one particular control of that type (such as txtEntry or List1). However, you can assign a particular
control to a variable of that type. For example, for a form with a list box called lstSample, you could write:

Dim objDemo As ListBox


Set objDemo = lstSample

Assigning Object Variables

You assign an object to an object variable with the Set statement:

Set variable = object

Use the Set statement whenever you want an object variable to refer to an object.

Sometimes you may use object variables, and particularly control variables, simply to shorten the code you have to type. For example, you might write code like this:

If frmAccountDisplay!txtAccountBalance.Text < 0 Then


frmAccountDisplay!txtAccountBalance.BackColor = 0 frmAccountDisplay!txtAccountBalance.ForeColor = 255
End If

You can shorten this code significantly if you use a control variable:

Dim Bal As TextBox


Set Bal = frmAccountDisplay!txtAccountBalance
If Bal.Text < 0 Then
Bal.BackColor = 0
Bal.ForeColor = 255
End If

Specific and Generic Object Types

Specific object variables must refer to one specific type of object or class. A specific form variable can refer to only one form in the application (though it can refer to one of many instances of
that form). Similarly, a specific control variable can refer to only one particular type of control in your application, such as TextBox or ListBox. To see an example, open a new project and place
a text box on a form. Add the following code to the form:

Private Sub Form_Click()


Dim anyText As TextBox
Set anyText = Text1
anyText.Text = "Hello"
End Sub

Run the application, and click the form. The Text property of the text box will be changed to "Hello."

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcreatingobjects.asp (2 of 6) [11/17/2002 10:51:54 PM]


Welcome to the MSDN Library
Generic object variables can refer to one of many specific types of objects. A generic form variable, for example, can refer to any form in an application; a generic control variable can refer to
any control on any form in an application. To see an example, open a new project and place several frame, label, and command button controls on a form, in any order. Add the following code
to the form:

Private Sub Form_Click()


Dim anyControl As Control
Set anyControl = Form1.Controls(3)
anyControl.Caption = "Hello"
End Sub

Run the application, and click the form. The caption of the control you placed third in sequence on the form will be changed to "Hello."

There are four generic object types in Visual Basic:

Generic Object
Type Object referenced

Form Any form in the application (including MDI children and the MDI form).

Control Any control in your application.

MDIForm The MDI form in the application (if your application has one).

Object Any object.

Generic object variables are useful when you don't know the specific type of object a variable will refer to at run time. For example, if you want to write code that can operate on any form in
the application, you must use a generic form variable.

Note Because there can be only one MDI form in the application, there is no need to use the generic MDIForm type. Instead, you can use the specific MDIForm type (MDIForm1, or whatever
you specified for the Name property of the MDI form) whenever you need to declare a form variable that refers to the MDI form. In fact, because Visual Basic can resolve references to
properties and methods of specific form types before you run your application, you should always use the specific MDIForm type.

The generic MDIForm type is provided only for completeness; should a future version of Visual Basic allow multiple MDI forms in a single application, it might become useful.

Forms as Objects

Forms are most often used to make up the interface of an application, but they're also objects that can be called by other modules in your application. Forms are closely related to class
modules. The major difference between the two is that forms can be visible objects, whereas class modules have no visible interface.

Adding Custom Methods and Properties


You can add custom methods and properties to forms and access them from other modules in your application. To create a new method for a form, add a procedure declared using Public.

' Custom method on Form1


Public Sub LateJobsCount()
.
. ' <statements>
.
End Sub

You can call the LateJobsCount procedure from another module using this statement:

Form1.LateJobsCount

Creating a new property for a form can be as simple as declaring a public variable in the form module:

Public IDNumber As Integer

You can set and return the value of IDNumber on Form1 from another module using these two statements:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcreatingobjects.asp (3 of 6) [11/17/2002 10:51:54 PM]


Welcome to the MSDN Library

Form1.IDNumber = 3
Text1.Text = Form1.IDNumber

You can also use Property procedures to add custom properties to a form.

For More Information Details on Property procedures are provided in "Programming with Objects."

Note You can call a variable, a custom method, or set a custom property on a form without loading the form. This allows you to run code on a form without loading it into memory. Also,
referencing a control without referencing one of its properties or methods does not load the form.

Using the New Keyword

Use the New keyword to create a new object as defined by its class. New can be used to create instances of forms, classes defined in class modules, and collections.

Using the New Keyword with Forms


Each form you create at design time is a class. The New keyword can be used to create new instances of that class. To see how this works, draw a command button and several other controls
on a form. Set the form's Name property to Sample in the Properties window. Add the following code to your command button's Click event procedure:

Dim x As New Sample


x.Show

Run the application, and click the command button several times. Move the front-most form aside. Because a form is a class with a visible interface, you can see the additional copies. Each
form has the same controls, in the same positions as on the form at design time.

Note To make a form variable and an instance of the loaded form persist, use a Static or Public variable instead of a local variable.

You can also use New with the Set statement. Try the following code in a command button's Click event procedure:

Dim f As Form1
Set f = New Form1
f.Caption = "hello"
f.Show

Using New with the Set statement is faster and is the recommended method.

Using the New Keyword with Other Objects


The New keyword can be used to create collections and objects from the classes you define in class modules. To see how this works, try the following example.

This example demonstrates how the New keyword creates instances of a class. Open a new project, and draw a command button on Form1. From the Project menu, choose Add Class Module to
add a class module to the project. Set the class module's Name property to ShowMe.

The following code in the Form1 module creates a new instance of the class ShowMe, and calls the procedure contained in the class module.

Public clsNew As ShowMe


Private Sub Command1_Click()
Set clsNew = New ShowMe
clsNew.ShowFrm
End Sub

The ShowFrm procedure in the class module creates a new instance of the class Form1, shows the form, and then minimizes it.

Sub ShowFrm()
Dim frmNew As Form1

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcreatingobjects.asp (4 of 6) [11/17/2002 10:51:54 PM]


Welcome to the MSDN Library
Set frmNew = New Form1
frmNew.Show
frmNew.WindowState = 1
End Sub

To use the example, run the application, and click the command button several times. You'll see a minimized form icon appear on your desktop as each new instance of the ShowMe class is
created.

For More Information For information on using New to create objects, see "Programming with Components."

New Keyword Restrictions


The following table describes what you cannot do with the New keyword.

You can't use New to create Example of code not allowed

Variables of fundamental data types. Dim X As New Integer

A variable of any generic object type. Dim X As New Control

A variable of any specific control type. Dim X As New ListBox

A variable of any specific control. Dim X As New lstNames

Freeing References to Objects

Each object uses memory and system resources. It is good programming practice to release these resources when you are no longer using an object.

● Use Unload to unload a form or control from memory.

● Use Nothing to release resources used by an object variable. Assign Nothing to an object variable with the Set statement.

For More Information See "Unload Event" and "Nothing" in the Language Reference.

Passing Objects to Procedures

You can pass objects to procedures in Visual Basic. In the following code example, it's assumed that there is a command button on a form:

Private Sub Command1_Click()


' Calls the Demo sub, and passes the form to it.
Demo Form1
End Sub

Private Sub Demo(x As Form1)


' Centers the form on the screen.
x.Left = (Screen.Width - x.Width) / 2
End Sub

It's also possible to pass an object to an argument by reference and then, inside the procedure, set the argument to a new object. To see how this works, open a project, and insert a second
form. Place a picture box control on each form. The following table shows the property settings that need changes:

Object Property Setting

Picture box on Form2 Name Picture2


Picture c:\vb\icons\arrows\arw01dn.ico

The Form1_Click event procedure calls the GetPicture procedure in Form2, and passes the empty picture box to it.

Private Sub Form_Click()


Form2.GetPicture Picture1
End Sub

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcreatingobjects.asp (5 of 6) [11/17/2002 10:51:54 PM]


Welcome to the MSDN Library
The GetPicture procedure in Form2 assigns the Picture property of the picture box on Form2 to the empty picture box on Form1.

Private objX As PictureBox


Public Sub GetPicture(x As PictureBox)
' Assign the passed-in picture box to an object
' variable.
Set objX = x
' Assign the value of the Picture property to Form1
' picture box.
objX.Picture = picture2.Picture
End Sub

To use the example, run the application, and click Form1. You'll see the icon from Form2 appear in the picture box on Form1.

For More Information The previous topics are intended to serve as an introduction to objects. To learn more, see "Programming with Objects" and "Programming with Components."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconcreatingobjects.asp (6 of 6) [11/17/2002 10:51:54 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 >

MSDN Library GO
Advanced Search Visual Basic Concepts

Programmer's Guide

See Also

Up One Level Welcome to the Visual Basic® Programmer’s Guide, a comprehensive manual on programming with Visual Basic. To accommodate the wealth of features and capabilities in Visual Basic, the
Programmer’s Guide is divided into two parts.
Part 1: Visual Basic Basics
Part 2: What Can You Do With Visual Basic? The first part covers the basic concepts, providing a foundation for programmers new to Visual Basic. Part 2 covers more advanced programming concepts and techniques. Additional
Visual Basic Specifications, Limitations, and File Formats information helpful in using the product is presented in the appendices.

Visual Basic Coding Conventions


Native Code Compiler Switches
Adding Help to Your Application Visual Basic Basics

An introduction to programming in Visual Basic.

What Can You Do With Visual Basic?

Advanced topics on Visual Basic programming.

Visual Basic Specifications, Limitations, and File Formats

Technical details for Visual Basic.

Visual Basic Coding Conventions

Suggested guidelines for consistent and readable code.

Native Code Compiler Switches

Details on command line switches for compiling to native code.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconProgrammersGuide.asp (1 of 2) [11/17/2002 10:59:59 PM]


Welcome to the MSDN Library
Adding Help to Your Application

Guidelines for adding online Help to a Visual Basic application.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconProgrammersGuide.asp (2 of 2) [11/17/2002 10:59:59 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 >

MSDN Library GO
Advanced Search Visual Basic Concepts

Data Access Guide

See Also

Up One Level Welcome to the Visual Basic® Data Access Guide. This documentation discusses data access and connects to information on related tools and technologies.

Accessing Data Using Visual Basic


Data Access Tools in Visual Basic This guide is divided into three parts. The first part covers tools and technology options. The second part presents tutorials that walk you through "scenarios" which employ the tools and
technologies in real-world situations. The third part presents information on two older Visual Basic data access technologies, DAO and RDO.
About the Data Environment Designer
Writing Reports with the Microsoft Data Report Designer Chapters
Interacting with Data in a Microsoft Jet/Microsoft Access Database
Create a DHTML Application that Interacts with SQL Server Data ● Accessing Data Using Visual Basic

Interacting with Data in an ASCII Text File


Introduces the different data access programming models available for accessing data, and discusses system and design issues that enter into a choice of a data access strategy. The emphasis is on ActiveX Data Objects (ADO), the new Microsoft technology.
Converting from RDO to ADO ● Data Access Tools in Visual Basic

Using Data Access Objects with Remote Databases


Using Remote Data Objects and the RemoteData Control Introduces mechanisms (such as the Query Designer and Database Designer) and technologies (such as Format Objects) that make data access programming easier.

● About the Data Environment Designer

This designer provides an extensive design-time interface that enables you to create and modify Data Environment objects.

● Writing Reports with the Microsoft Data Report Designer

This designer allows you to generate data reports from several different relational tables.

● Tutorial: Interacting with Data in a Microsoft Jet/Microsoft Access Database

Demonstrates how to use a data environment to create a Command object based on a Microsoft Access query, bind Visual Basic controls to fields in the query's recordset, create a master/detail form, and create a data-bound report.

● Tutorial: Create a DHTML Application that Interacts with SQL Server Data

Demonstrates how to create an application that adds a table to an SQL Server database; uses HTML pages to enter, view, and update data in the table; and uses an HTML page to view data returned by a stored procedure.

● Tutorial: Interacting with Data in an ASCII Text File

Demonstrates how to use a data-aware class and ADO to create a simple database application that interacts with data in a tab-delimited text file.

● Converting from RDO 2.0 to ADO 2.0

Discusses the changes needed to upgrade an existing RDO-based project to Microsoft's new data access technology.

● Using Data Access Objects with Remote Databases

Data Access Objects (DAO) is an older database technology that can be used either with the standalone Microsoft Jet database engine, or with direct access to remote data sources through the new ODBCDirect option. This section discusses DAO functionality
in both modes, emphasizing the special design considerations of large scale client/server applications.

● Using Remote Data Objects and the RemoteData Control

Remote Data Objects (RDO) is an older database technology that provides a direct Visual Basic interface to remote ODBC data sources, and the RemoteData Control (RDC) makes this functionality available in a simple user interface control. This chapter
provides a thorough discussion of the RDO/RDC features and functionality in client/server applications.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbcondataaccessguide.asp [11/17/2002 11:00:32 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)

MSDN Library GO
Advanced Search Visual Basic Concepts

Accessing Data Using Visual Basic

See Also

Up One Level The figure below is a roadmap of data access technologies found in Visual Basic. The figure features "hot" zones, which you can click to find out more information about any particular set of
data, access tools or technologies.
Forms and Data-Aware Controls
ADO, DAO, and RDO in Visual Basic
OLE DB Providers
Visual Basic Data Sources
Visual Basic and Microsoft Transaction Server
Data Binding In Visual Basic
Remoting Features of Visual Basic
DHTML and Visual Basic Data Access

Microsoft Visual Data Tools

Using Visual Basic 6.0 you can create components that encapsulate every step in a data access system. Beginning with the data source, Microsoft Visual Data Tools (accessible through the
Data View window) give you the ability to view and manipulate tables, views, stored procedures, and database schemas on SQL Server and Oracle systems.

Middle Tier Components and Microsoft Transaction Server


The power of Visual Basic is also leveraged to create the middle tier components in your application, as you make your own ActiveX DLLs and EXEs. Visual Basic now includes enhancements
that tailor applications to work with Microsoft Transaction Server.

ActiveX Data Objects (ADO)


The bridge between the data providers and data consumers is through data sources created using Microsoft ActiveX Data Objects (ADO), which is the primary method in Visual Basic to access
data in any data source, both relational and non-relational. For backward compatibility and project maintenance, Remote Data Objects (RDO) and Data Access Objects (DAO) are still

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAccessingData.asp (1 of 3) [11/17/2002 11:00:39 PM]


Welcome to the MSDN Library
supported.

Data Sources and Data Controls


On the client side, several new data sources are available, including the Data Environment, a graphical designer that allows you to quickly create ADO Connections and Commands to access
your data. The Data Environment designer provides a dynamic programmatic interface to the data access objects in your project. In addition, the Data Environment provides advanced data
shaping services — the ability to create hierarchies of related data, aggregates, and automatic groupings, all without code.

The new ADO Data control is similar to the intrinsic data control and Remote Data control, except that it uses ADO to access data. You can now use an ADO Recordset as a data source for your
controls and objects in Visual Basic.

In Visual Basic you can now create your own data sources either as user controls or classes, to encapsulate business rules or proprietary data structures. The class module now features the
DataSourceBehavior property and the GetDataMember event, which allow you to configure a class as a data source.

Dynamic Data Binding


The ability to dynamically bind a data source to a data consumer is now possible in Visual Basic. At run time, you can now set the DataSource property of a data consumer (such as the
DataGrid control) to a data source (such as the ADO Data control). This capability, unavailable in previous versions of Visual Basic, allows you to create applications, which can access a
multitude of data sources.

Presenting Data to the End User


Visual Basic offers a variety of rich ways to present data to your end users. ADO/OLE DB-based versions of all the data bound controls are included in Visual Basic:

● The DataList and DataCombo controls are the ADO/OLE DB equivalents of DBList and DBCombo controls.

● The DataGrid is the successor to DBGrid.

● The Chart control is now data bound.

● A new version of the FlexGrid control, called the Hierarchical FlexGrid, supports the hierarchical abilities of the Data Environment.

● The new DataRepeater control functions as a scrolling container of data bound user controls where each control views a single record.

The Data Report is a new ActiveX designer that creates reports from any data source, including the Data Environment. With the Data Report designer, formatted reports can be viewed online,
printed, or exported to text or HTML pages.

Data Formatting and Data Validation


The new DataFormat object allows you to display data with custom formatting, but write it back to the database in the native format. For example, you can now display dates in the format
appropriate to a country, while the actual data is stored in a date format. Data is formatted coming out of the source, and unformatted going back in. You can also do custom formatting and
perform additional checks using the Format and Unformat events.

Data validation is also enhanced using the CausesValidation property with the Validate event. By setting the CausesValidation property to True, the Validate event for the previous control in the
tab order will occur. Thus, by programming the Validate event, you can prevent a control from losing focus until the information it contains has been validated.

Language Features
New data-related enhancements to the Visual Basic language include the ability to pass User-defined Types (UDTs) and arrays across processes. You can now define a UDT and pass it as a
parameter to another process, such as an ActiveX EXE or DLL.

DHTML and Data Access


Using Visual Basic, you can create complete web applications for data access. All of the data tools and technologies can also be used in DHTML pages, and on web server (IIS) applications.

Other Enterprise features

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAccessingData.asp (2 of 3) [11/17/2002 11:00:39 PM]


Welcome to the MSDN Library
For information on data access programming in the enterprise, see Data Access Strategies in Developing for the Enterprise.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAccessingData.asp (3 of 3) [11/17/2002 11:00:39 PM]


Forms and Data-Aware Controls

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

Visual Basic Concepts

Forms and Data-Aware Controls

See Also

To create interfaces for data entry, data editing, or data viewing, Visual Basic forms and controls have always offered versatility and ease of programming.

In version 6.0, several new data-aware (data-bound) controls have been added. In addition to these new controls, the new Validate event and CausesValidation property prevent a control from
losing focus until all data has been validated. For example, you can create data-entry forms that validate data by preventing the user from tabbing off the form until all fields have been filled in.

Another enhancement always available to you is the Microsoft Data Formatting Object Library. This new object library allow you to format data and preserve the underlying format to write back to
the database.

New Data-Aware Controls


Several new ActiveX controls, specifically designed to view and/or edit data, have been added. These include:

● DataGrid Control — a new grid control that can work with the ADO Data Control or ADO Recordset objects.

● DataList Control — a control that functions exactly like the DBList control, but is optimized for use with OLE DB data sources.

● DataCombo Control — functions like the DBCombo control, but can use OLE DB data sources.

● Hierarchical FlexGrid Control — capable of displaying hierarchical cursors created with the Data Environment.

● DataRepeater Control — lets you use a user control to display data, and "repeats" the control to view multiple records.

● MonthView Control — displays dates graphically as a calendar.

● DateTimePicker Control — similarly to the MonthView control, it displays dates in a text box; clicking the text box causes a graphic calendar to drop down for selection of a new date.

Data Binding Capabilities Added to Existing Controls


Intrinsic controls and many ActiveX Controls have new data properties associated with them now, in addition to the DataSource and DataField properties that have always existed. These are the
four properties of interest:

● DataSource Property: Returns or sets the source of data for a control. You can now dynamically set the DataSource of a control or object at runtime to any valid data source, for example: an ADO Recordset, the DataEnvironment, a class that’s a data source, or to
a data source control on the form.

● DataMember Property: Returns or sets the specific data set within the source to use. Data sources in Visual Basic 6.0 can contain multiple sets of data, and the DataMember property lets you specify which set of data to use. (Not all data sources have multiple
members, for example the ADO Data Control returns only a single recordset.) The Data Environment, on the other hand, returns a DataMember for each Command defined. Visual Basic displays a list of available data members when this property is selected.

● DataField Property: Returns or sets the specific field to bind a control to. (Same functionality as in previous versions of Visual Basic.)

● DataFormat Property: Lets you define the automatic formatting of data as its retrieved from the data source.

The first three properties narrow in scope, from the DataSource down to the DataField, qualifying the source of the data. However, for complex data consumers such as the DataGrid, the DataField
and DataFormat properties aren’t required, as the control handles them for you. For more information about the difference between simple-bound and complex-bound controls, see Creating Data-
Aware Classes.

The controls which can be data bound using some or all of these properties include:

● CheckBox Control

● ComboBox Control

● DataCombo Control (new)

● DataGrid Control (new)

● DataList Control (new)

● DataRepeater Control (new)

● DateTimePicker Control (new)

● DBCombo Control

● DBList Control

● FlexGrid Control

● Hierarchical FlexGrid Control (new)

● Image Control

● ImageCombo Control (new)

● Label Control

● ListBox Control

● Masked Edit Control

● MonthView Control (new)

● MSChart Control

● PictureBox Control

● RichTextBox Control

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconDataAwareControls.asp?frame=true (1 of 2) [11/17/2002 11:00:44 PM]


Forms and Data-Aware Controls

● TextBox Control

Additionally, the new Extender object also includes the DataSource, DataMember, and DataField properties. The Extender object is used to program controls added dynamically to your forms. For
more information on the Extender and adding controls at run time, see Add Method (Controls Collection) and Extender Object.

Validation Enhancements
Data validation is now easier using the Validate event with the CausesValidation property. Using the two new features in tandem, you can prevent a control from losing focus until the information it
contains has been validated. For more information about these features, see Validating Control Data by Restricting Focus.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconDataAwareControls.asp?frame=true (2 of 2) [11/17/2002 11:00:44 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Forms and Data-Aware Controls

See Also

Up One Level To create interfaces for data entry, data editing, or data viewing, Visual Basic forms and controls have always offered versatility and ease of programming.

Forms and Data-Aware Controls


ADO, DAO, and RDO in Visual Basic In version 6.0, several new data-aware (data-bound) controls have been added. In addition to these new controls, the new Validate event and CausesValidation property prevent a control from
losing focus until all data has been validated. For example, you can create data-entry forms that validate data by preventing the user from tabbing off the form until all fields have been filled
OLE DB Providers in.

Visual Basic Data Sources


Visual Basic and Microsoft Transaction Server Another enhancement always available to you is the Microsoft Data Formatting Object Library. This new object library allow you to format data and preserve the underlying format to write back
to the database.
Data Binding In Visual Basic
Remoting Features of Visual Basic
DHTML and Visual Basic Data Access New Data-Aware Controls
Several new ActiveX controls, specifically designed to view and/or edit data, have been added. These include:

● DataGrid Control — a new grid control that can work with the ADO Data Control or ADO Recordset objects.

● DataList Control — a control that functions exactly like the DBList control, but is optimized for use with OLE DB data sources.

● DataCombo Control — functions like the DBCombo control, but can use OLE DB data sources.

● Hierarchical FlexGrid Control — capable of displaying hierarchical cursors created with the Data Environment.

● DataRepeater Control — lets you use a user control to display data, and "repeats" the control to view multiple records.

● MonthView Control — displays dates graphically as a calendar.

● DateTimePicker Control — similarly to the MonthView control, it displays dates in a text box; clicking the text box causes a graphic calendar to drop down for selection of a new date.

Data Binding Capabilities Added to Existing Controls


Intrinsic controls and many ActiveX Controls have new data properties associated with them now, in addition to the DataSource and DataField properties that have always existed. These are
the four properties of interest:

● DataSource Property: Returns or sets the source of data for a control. You can now dynamically set the DataSource of a control or object at runtime to any valid data source, for example: an ADO Recordset, the DataEnvironment, a class that’s a data source,
or to a data source control on the form.

● DataMember Property: Returns or sets the specific data set within the source to use. Data sources in Visual Basic 6.0 can contain multiple sets of data, and the DataMember property lets you specify which set of data to use. (Not all data sources have multiple
members, for example the ADO Data Control returns only a single recordset.) The Data Environment, on the other hand, returns a DataMember for each Command defined. Visual Basic displays a list of available data members when this property is selected.

● DataField Property: Returns or sets the specific field to bind a control to. (Same functionality as in previous versions of Visual Basic.)

● DataFormat Property: Lets you define the automatic formatting of data as its retrieved from the data source.

The first three properties narrow in scope, from the DataSource down to the DataField, qualifying the source of the data. However, for complex data consumers such as the DataGrid, the
DataField and DataFormat properties aren’t required, as the control handles them for you. For more information about the difference between simple-bound and complex-bound controls, see
Creating Data-Aware Classes.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDataAwareControls.asp (1 of 2) [11/17/2002 11:00:46 PM]


Welcome to the MSDN Library
The controls which can be data bound using some or all of these properties include:

● CheckBox Control

● ComboBox Control

● DataCombo Control (new)

● DataGrid Control (new)

● DataList Control (new)

● DataRepeater Control (new)

● DateTimePicker Control (new)

● DBCombo Control

● DBList Control

● FlexGrid Control

● Hierarchical FlexGrid Control (new)

● Image Control

● ImageCombo Control (new)

● Label Control

● ListBox Control

● Masked Edit Control

● MonthView Control (new)

● MSChart Control

● PictureBox Control

● RichTextBox Control

● TextBox Control

Additionally, the new Extender object also includes the DataSource, DataMember, and DataField properties. The Extender object is used to program controls added dynamically to your forms.
For more information on the Extender and adding controls at run time, see Add Method (Controls Collection) and Extender Object.

Validation Enhancements
Data validation is now easier using the Validate event with the CausesValidation property. Using the two new features in tandem, you can prevent a control from losing focus until the
information it contains has been validated. For more information about these features, see Validating Control Data by Restricting Focus.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDataAwareControls.asp (2 of 2) [11/17/2002 11:00:46 PM]


ADO, DAO and RDO in Visual Basic

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

Visual Basic Concepts

ADO, DAO and RDO in Visual Basic

See Also

In Visual Basic, three data access interfaces are available to you: ActiveX Data Objects (ADO), Remote Data Objects (RDO), and Data Access Objects (DAO). A data access interface is an object
model that represents various facets of accessing data. Using Visual Basic, you can programmatically control the connection, statement builders, and returned data for use in any application.

Why are there three data access interfaces in Visual Basic? Data access technology is constantly evolving, and each of the three interfaces represent a different state of the art. The latest is ADO,
which features a simpler — yet more flexible — object model than either RDO or DAO. For new projects, you should use ADO as your data access interface.

Why Use ADO?

ADO is designed as an easy-to-use application level interface to Microsoft's newest and most powerful data access paradigm, OLE DB. OLE DB provides high-performance access to any data
source, including relational and non-relational databases, email and file systems, text and graphics, custom business objects, and more. ADO is implemented for minimal network traffic in key
Internet scenarios, and a minimal number of layers between the front-end and data source — all to provide a lightweight, high-performance interface. ADO is called using a familiar metaphor —
the OLE Automation interface. And ADO uses conventions and features similar to DAO and RDO, with simplified semantics that make it easy to learn.

For a brief overview, see OLE DB Providers.

For detailed information about ADO, see the Introduction to the "ADO Programmer's Guide."

DAO and RDO


For backward compatibility, Visual Basic continues to support DAO and RDO for existing projects.

For More Information For more information on RDO programming, see Using Remote Data Objects and the RemoteData Control. For information on DAO programming, see Using Data Access
Objects with Remote Databases. Complete DAO reference can also be found at Microsoft DAO 3.6.

Upgrading from RDO to ADO


Consider upgrading if you decide ADO offers benefits your RDO-based application can use. See ADO Compared with RDO and DAO for a discussion of the differences among the platforms and for
guidance on changing an RDO-based project to an ADO project. See Converting from RDO 2.0 to ADO 2.0 for upgrade guidance.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconUsingADODAORDOInVisualBasic.asp?frame=true [11/17/2002 11:00:53 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

ADO, DAO and RDO in Visual Basic

See Also

Up One Level In Visual Basic, three data access interfaces are available to you: ActiveX Data Objects (ADO), Remote Data Objects (RDO), and Data Access Objects (DAO). A data access interface is an
object model that represents various facets of accessing data. Using Visual Basic, you can programmatically control the connection, statement builders, and returned data for use in any
Forms and Data-Aware Controls application.

ADO, DAO, and RDO in Visual Basic


OLE DB Providers Why are there three data access interfaces in Visual Basic? Data access technology is constantly evolving, and each of the three interfaces represent a different state of the art. The latest is
ADO, which features a simpler — yet more flexible — object model than either RDO or DAO. For new projects, you should use ADO as your data access interface.
Visual Basic Data Sources
Visual Basic and Microsoft Transaction Server Why Use ADO?
Data Binding In Visual Basic
Remoting Features of Visual Basic ADO is designed as an easy-to-use application level interface to Microsoft's newest and most powerful data access paradigm, OLE DB. OLE DB provides high-performance access to any data
source, including relational and non-relational databases, email and file systems, text and graphics, custom business objects, and more. ADO is implemented for minimal network traffic in key
DHTML and Visual Basic Data Access Internet scenarios, and a minimal number of layers between the front-end and data source — all to provide a lightweight, high-performance interface. ADO is called using a familiar metaphor
— the OLE Automation interface. And ADO uses conventions and features similar to DAO and RDO, with simplified semantics that make it easy to learn.

For a brief overview, see OLE DB Providers.

For detailed information about ADO, see the Introduction to the "ADO Programmer's Guide."

DAO and RDO


For backward compatibility, Visual Basic continues to support DAO and RDO for existing projects.

For More Information For more information on RDO programming, see Using Remote Data Objects and the RemoteData Control. For information on DAO programming, see Using Data
Access Objects with Remote Databases. Complete DAO reference can also be found at Microsoft DAO 3.6.

Upgrading from RDO to ADO


Consider upgrading if you decide ADO offers benefits your RDO-based application can use. See ADO Compared with RDO and DAO for a discussion of the differences among the platforms and
for guidance on changing an RDO-based project to an ADO project. See Converting from RDO 2.0 to ADO 2.0 for upgrade guidance.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingADODAORDOInVisualBasic.asp (1 of 2) [11/17/2002 11:00:55 PM]


Welcome to the MSDN Library
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingADODAORDOInVisualBasic.asp (2 of 2) [11/17/2002 11:00:55 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

OLE DB Providers

See Also

Up One Level OLE DB is a new low-level interface that introduces a "universal" data access paradigm. That is, OLE DB is not restricted to ISAM, Jet, or even relational data sources, but is capable of dealing
with any type of data regardless of its format or storage method. In practice, this versatility means you can access data that resides in an Excel spreadsheet, text files, or even on a mail server
Forms and Data-Aware Controls such as Microsoft Exchange.

ADO, DAO, and RDO in Visual Basic


OLE DB Providers In Visual Basic 6.0, you leverage the flexibility of OLE DB through ADO, the programmer interface to OLE DB.

Visual Basic Data Sources


Visual Basic and Microsoft Transaction Server OLE DB and ADO
Data Binding In Visual Basic
Remoting Features of Visual Basic OLE DB is not designed to be accessed directly from Visual Basic due to its complex interfaces. Instead ActiveX Data Objects (ADO) encapsulates and exposes virtually all of OLE DB’s
functionality.
DHTML and Visual Basic Data Access

For More Information For more background on OLE DB see Microsoft OLE DB Overview.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconoledbproviders.asp [11/17/2002 11:02:57 PM]


OLE DB Providers

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

Visual Basic Concepts

OLE DB Providers

See Also

OLE DB is a new low-level interface that introduces a "universal" data access paradigm. That is, OLE DB is not restricted to ISAM, Jet, or even relational data sources, but is capable of dealing with
any type of data regardless of its format or storage method. In practice, this versatility means you can access data that resides in an Excel spreadsheet, text files, or even on a mail server such as
Microsoft Exchange.

In Visual Basic 6.0, you leverage the flexibility of OLE DB through ADO, the programmer interface to OLE DB.

OLE DB and ADO


OLE DB is not designed to be accessed directly from Visual Basic due to its complex interfaces. Instead ActiveX Data Objects (ADO) encapsulates and exposes virtually all of OLE DB’s functionality.

For More Information For more background on OLE DB see Microsoft OLE DB Overview.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconOLEDBProviders.asp?frame=true [11/17/2002 11:03:19 PM]


Visual Basic Data Sources

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

Visual Basic Concepts

Visual Basic Data Sources

See Also

As the term implies, a data source is a readily accessible object that provides data to any data consumer (any class or control that can be bound to a source of external data). In past versions of
Visual Basic, data sources included the intrinsic Data control and the RemoteData Control. Visual Basic 6.0 introduces several new data sources that enable you to create rich applications to view
and edit data. For example, the Data Environment designer allows you to create hierarchical recordsets, or data from several related tables in a tree-view format. In addition to new data sources,
you can create your own data source by setting the class module's DataSourceBehavior property to vbDataSource.

New Data Sources


Visual Basic's new richer set of data sources includes:

● Data-Aware Class Modules

● Data-Aware User Controls

● Data Environment

● ADO Recordset Objects

● ADO Data Control

Creating Data Sources Using Data-Aware Classes and User


Controls
Visual Basic enables you to create your own data sources. Using new features such as the DataBindingBehavior and DataSourceBehavior properties of the class module, you can encapsulate the
methods, properties, and events necessary to create a data source or data consumer that accesses data from any kind of database. For details on creating data sources and data consumers using
a data-aware class, see Creating Data-Aware Classes.

In addition to creating data-aware classes, you can also create your own data-aware user controls. Such a control could resemble the new ADO Data Control and be customized to your needs. For
a step-by-step example of creating a data-aware user control, see Creating the MyDataControl Project.

The Data Environment Designer


The Data Environment is a new feature that allows you to create hierarchical cursors. A hierarchical cursor is a unique structure of parent and child recordsets. In general, a hierarchical cursor
mirrors the structure of related tables in a relational database. For example, the Northwind database has a table named "Products" that contains a field named "SupplierID." That field contains
unique IDs from the related table named "Suppliers." Using the Data Environment designer, you can create a hierarchical cursor that can be displayed in a control such as the Hierarchical FlexGrid
control.

For details about hierarchical cursors, see Hierarchical Cursors and Data Shaping. For details about the DataEnvironment, see About the Data Environment Designer.

Creatable ADO Recordsets


Using the ActiveX Data Object Recordset (ADOR) library, you can create ADO recordsets in memory, as shown below:

Private rs As New ADODB.Recordset ' variable for recordset

Private Sub CreateRecordset()


With rs
.Fields.Append "ID", adInteger
.Fields.Append "Item", adVarChar, 255
.CursorType = adOpenStatic
.LockType = adLockOptimistic
.Open ' No connection object needed.
End With
Dim i As Integer

For i = 1 To 100
rs.AddNew
rs!ID= i
rs!Item = "thing " & i
rs.Update
Next i
rs.MoveFirst
End Sub

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconVisualBasicDataSources.asp?frame=true (1 of 2) [11/17/2002 11:03:23 PM]


Visual Basic Data Sources

Once such a recordset is filled with data, set the DataSource property of a data consumer to the recordset, as shown below:

' myControl is a data-bound user control and rsTempData is a temporary


' recordset created using ADODB, and filled from some data store.
Set myControl.DataSource = rs

For an example of creating ADO recordsets in code, see Creating a Data Source. Another example of creating a recordset and using it as a data source for the DataGrid control can be found in
Using the DataGrid Control with a Class Module.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconVisualBasicDataSources.asp?frame=true (2 of 2) [11/17/2002 11:03:23 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Visual Basic Data Sources

See Also

Up One Level As the term implies, a data source is a readily accessible object that provides data to any data consumer (any class or control that can be bound to a source of external data). In past versions
of Visual Basic, data sources included the intrinsic Data control and the RemoteData Control. Visual Basic 6.0 introduces several new data sources that enable you to create rich applications to
Forms and Data-Aware Controls view and edit data. For example, the Data Environment designer allows you to create hierarchical recordsets, or data from several related tables in a tree-view format. In addition to new data
sources, you can create your own data source by setting the class module's DataSourceBehavior property to vbDataSource.
ADO, DAO, and RDO in Visual Basic
OLE DB Providers
Visual Basic Data Sources New Data Sources
Visual Basic and Microsoft Transaction Server
Data Binding In Visual Basic Visual Basic's new richer set of data sources includes:

Remoting Features of Visual Basic


DHTML and Visual Basic Data Access ●


Data-Aware Class Modules

Data-Aware User Controls

● Data Environment

● ADO Recordset Objects

● ADO Data Control

Creating Data Sources Using Data-Aware Classes and User


Controls
Visual Basic enables you to create your own data sources. Using new features such as the DataBindingBehavior and DataSourceBehavior properties of the class module, you can encapsulate
the methods, properties, and events necessary to create a data source or data consumer that accesses data from any kind of database. For details on creating data sources and data
consumers using a data-aware class, see Creating Data-Aware Classes.

In addition to creating data-aware classes, you can also create your own data-aware user controls. Such a control could resemble the new ADO Data Control and be customized to your needs.
For a step-by-step example of creating a data-aware user control, see Creating the MyDataControl Project.

The Data Environment Designer


The Data Environment is a new feature that allows you to create hierarchical cursors. A hierarchical cursor is a unique structure of parent and child recordsets. In general, a hierarchical cursor
mirrors the structure of related tables in a relational database. For example, the Northwind database has a table named "Products" that contains a field named "SupplierID." That field contains
unique IDs from the related table named "Suppliers." Using the Data Environment designer, you can create a hierarchical cursor that can be displayed in a control such as the Hierarchical
FlexGrid control.

For details about hierarchical cursors, see Hierarchical Cursors and Data Shaping. For details about the DataEnvironment, see About the Data Environment Designer.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconVisualBasicDataSources.asp (1 of 2) [11/17/2002 11:03:25 PM]


Welcome to the MSDN Library

Creatable ADO Recordsets


Using the ActiveX Data Object Recordset (ADOR) library, you can create ADO recordsets in memory, as shown below:

Private rs As New ADODB.Recordset ' variable for recordset

Private Sub CreateRecordset()


With rs
.Fields.Append "ID", adInteger
.Fields.Append "Item", adVarChar, 255
.CursorType = adOpenStatic
.LockType = adLockOptimistic
.Open ' No connection object needed.
End With
Dim i As Integer

For i = 1 To 100
rs.AddNew
rs!ID= i
rs!Item = "thing " & i
rs.Update
Next i
rs.MoveFirst
End Sub

Once such a recordset is filled with data, set the DataSource property of a data consumer to the recordset, as shown below:

' myControl is a data-bound user control and rsTempData is a temporary


' recordset created using ADODB, and filled from some data store.
Set myControl.DataSource = rs

For an example of creating ADO recordsets in code, see Creating a Data Source. Another example of creating a recordset and using it as a data source for the DataGrid control can be found in
Using the DataGrid Control with a Class Module.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconVisualBasicDataSources.asp (2 of 2) [11/17/2002 11:03:25 PM]


Visual Basic and Microsoft Transaction Server

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

Visual Basic Concepts

Visual Basic and Microsoft Transaction Server

See Also

The ability to build middle-tier components — ActiveX EXEs and DLLs — is not new to Visual Basic. What's new to Version 6.0 is the ability to tailor your components to run in conjunction with
Microsoft Transaction Server (MTS).

Microsoft Transaction Server is a component-based transaction processing system for developing, deploying, and managing high performance, scalable, and robust server applications. MTS defines
a programming model and provides a run-time environment and graphical administration tool for managing enterprise applications.

Using the new MTSTransactionMode property of the class module, you can create components that ignore MTS, or support transactions by setting a property. When the component is not running
in an MTS environment, the property is ignored.

For More Information For more information about MTS, see Quick Tour of Microsoft Transaction Server. For information about the MTSTransactionMode property, see MTSTransactionMode
Property. For information about using Visual Basic, MTS, and Microsoft Message Queue, see Visual Basic and the Microsoft Message Queue.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconMiddleTierComponents.asp?frame=true [11/17/2002 11:03:29 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Visual Basic and Microsoft Transaction Server

See Also

Up One Level The ability to build middle-tier components — ActiveX EXEs and DLLs — is not new to Visual Basic. What's new to Version 6.0 is the ability to tailor your components to run in conjunction with
Microsoft Transaction Server (MTS).
Forms and Data-Aware Controls
ADO, DAO, and RDO in Visual Basic Microsoft Transaction Server is a component-based transaction processing system for developing, deploying, and managing high performance, scalable, and robust server applications. MTS
OLE DB Providers defines a programming model and provides a run-time environment and graphical administration tool for managing enterprise applications.

Visual Basic Data Sources


Visual Basic and Microsoft Transaction Server Using the new MTSTransactionMode property of the class module, you can create components that ignore MTS, or support transactions by setting a property. When the component is not
running in an MTS environment, the property is ignored.
Data Binding In Visual Basic
Remoting Features of Visual Basic For More Information For more information about MTS, see Quick Tour of Microsoft Transaction Server. For information about the MTSTransactionMode property, see MTSTransactionMode
DHTML and Visual Basic Data Access Property. For information about using Visual Basic, MTS, and Microsoft Message Queue, see Visual Basic and the Microsoft Message Queue.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconMiddleTierComponents.asp [11/17/2002 11:03:31 PM]


Data Binding In Visual Basic

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

Visual Basic Concepts

Data Binding In Visual Basic

See Also

In previous versions of Visual Basic, binding a data source (such as the Data control) to a data consumer (such as the DBCombo control or simply to a text box) could only be done at design-time.
Visual Basic now allows you to bind almost any data source to any data consumer at run time. For example, at run time, you can now set the DataSource property as shown below:

Text1.DataMember = "Employees"
Text1.DataField = "Salary"
Set Text1.DataSource = DataEnvironment1

With this capability, you can also bind controls that have been added to the Controls collection using the new Add method. The code below adds a user control and binds it.

Private myCtl As Extender


Form1.Licenses.Add "Project1.userControl1", "uc1_Key"
Set myCtl = Form1.Controls.Add("Project1.userControl1", "Ctl_Key")
myCtl.DataMember = "Employees"
myCtl.DataField = "Salary"
Set myCtl.DataSource = DataEnvironment1

Exceptions

The only data sources that cannot be bound in this manner are the intrinsic Data control and the RemoteData Control.

The BindingCollection Object


In addition to this flexibility, you can also create your own data source using new data-aware features of the class module. Once you have created such a data source, you can also bind it at run
time to a data consumer using the BindingCollection object. For details, see Creating Data-Aware Classes and Creating a Data Source.

Data-Aware User Controls


Visual Basic 6.0 also allows you to create your own user controls that function as data sources.

For More Information For more information about new data-bound controls, see Forms and Data-Aware Controls.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconDataBindingInVisualBasic.asp?frame=true [11/17/2002 11:03:36 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Data Binding In Visual Basic

See Also

Up One Level In previous versions of Visual Basic, binding a data source (such as the Data control) to a data consumer (such as the DBCombo control or simply to a text box) could only be done at design-
time. Visual Basic now allows you to bind almost any data source to any data consumer at run time. For example, at run time, you can now set the DataSource property as shown below:
Forms and Data-Aware Controls
ADO, DAO, and RDO in Visual Basic Text1.DataMember = "Employees"
OLE DB Providers Text1.DataField = "Salary"
Set Text1.DataSource = DataEnvironment1
Visual Basic Data Sources
Visual Basic and Microsoft Transaction Server With this capability, you can also bind controls that have been added to the Controls collection using the new Add method. The code below adds a user control and binds it.

Data Binding In Visual Basic


Remoting Features of Visual Basic Private myCtl As Extender
Form1.Licenses.Add "Project1.userControl1", "uc1_Key"
DHTML and Visual Basic Data Access Set myCtl = Form1.Controls.Add("Project1.userControl1", "Ctl_Key")
myCtl.DataMember = "Employees"
myCtl.DataField = "Salary"
Set myCtl.DataSource = DataEnvironment1

Exceptions

The only data sources that cannot be bound in this manner are the intrinsic Data control and the RemoteData Control.

The BindingCollection Object


In addition to this flexibility, you can also create your own data source using new data-aware features of the class module. Once you have created such a data source, you can also bind it at
run time to a data consumer using the BindingCollection object. For details, see Creating Data-Aware Classes and Creating a Data Source.

Data-Aware User Controls


Visual Basic 6.0 also allows you to create your own user controls that function as data sources.

For More Information For more information about new data-bound controls, see Forms and Data-Aware Controls.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDataBindingInVisualBasic.asp (1 of 2) [11/17/2002 11:03:38 PM]


Welcome to the MSDN Library
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDataBindingInVisualBasic.asp (2 of 2) [11/17/2002 11:03:38 PM]


Remoting Features of Visual Basic

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

Visual Basic Concepts

Remoting Features of Visual Basic

See Also

"Remoting" is the process of passing parameters between two different processes, usually across a network. For example, imagine a three-tier system. On the client machine, the application
makes a call for data, passing several parameters as the criteria. On the middle-tier machine, an ActiveX EXE accepts the call and uses the criteria for retrieving the data.

For example, code on a middle-tier application might resemble:

Option Explicit

' This code is in a code module.


Public Type udtMyType ' Definition of a Public UDT
birthDate As Date
lastName As String
firstName As String
address As String
End Type

Public Function passUDT(myrec As udtMyType) As udtMyType


' Modify the data somehow.
passUDT = myrec ' Return the UDT.
End Function

While code on the client machine that calls the function would be:

Option Explicit
Private myrec As udtMyType

Private Sub Command1_Click()


Dim x As udtMyType
x = passUDT(myrec)
' Do something with the UDT data.
End Sub

Passing a UDT as a Parameter of a Public Sub


While passing parameters has always been possible in previous versions of Visual Basic, passing user-defined types (UDTs) as parameters of public subs has not. This is now possible, as shown in
the example above.

Performance Considerations
The cost of passing parameters out-of-process is far higher than passing them in-process. When passing a parameter, the data must be marshaled and passed to the external process. The code to
accomplish this action can be expensive, but Visual Basic conceals this cost. The advantage of remoting data, however, is to create code that is easily comprehensible. Depending on the size of the
UDT, it may also be easier to maintain than an ADO Recordset object.

For More Information For details about creating and using UDTs, see Creating Your Own Data Types.

Remoting ADO Recordsets


ADO Recordset objects can also be remoted. With this capability, ADO recordsets are especially suited for use on intranet and Internet client-server applications. For example, you can create an
HTML or DHTML page that accesses data across the Internet from a web server application. When creating the HTML page, you can include the Microsoft ActiveX Data Access Recordset 2.0 Library,
which features only the Recordset object. Since that library doesn't include the Command, Connection, and Parameter objects, your application will have the smallest possible footprint while
retaining the functionality of the ADO Recordset features. The code below shows an example of remoting ADO recordsets.

' This code is in a code module.


' Set a reference to the Microsoft ActiveX Data Objects 2.0 Library
Private MyADORecordset As ADODB.Recordset

Public Function GetCustomer(LastName As String) As ADODB.Recordset


' Query the DB
MyADORecordset.Open "SELECT * FROM Customers WHERE " & _
"LastName = '" & LastName & "'", cn, adOpenForwardOnly, adLockReadOnly
Set MyADORecordset.ActiveConnection = Nothing
Set GetCustomer = MyADORecordset ' Return the recordset.
End Function

While code on the client machine that calls the function would be:

http://msdn.microsoft.com/library/en-us/vbcon98/...bconRemotingFeaturesOfVisualBasic.asp?frame=true (1 of 2) [11/17/2002 11:03:42 PM]


Remoting Features of Visual Basic

Option Explicit
Private SomeServer As Object

Private Sub Command1_Click()


' Client can use the lighter ADOR library. Set a reference to
' the Microsoft ActiveX Data Objects Recordset 2.0 Library.
Dim MyData As ADOR.Recordset
Set SomeServer = CreateObject("foo.bar", myserver)
Set MyData = SomeServer.GetCustomer("Smith")
' Do something with the data.
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/...bconRemotingFeaturesOfVisualBasic.asp?frame=true (2 of 2) [11/17/2002 11:03:42 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Remoting Features of Visual Basic

See Also

Up One Level "Remoting" is the process of passing parameters between two different processes, usually across a network. For example, imagine a three-tier system. On the client machine, the application
makes a call for data, passing several parameters as the criteria. On the middle-tier machine, an ActiveX EXE accepts the call and uses the criteria for retrieving the data.
Forms and Data-Aware Controls
ADO, DAO, and RDO in Visual Basic For example, code on a middle-tier application might resemble:
OLE DB Providers
Visual Basic Data Sources Option Explicit
Visual Basic and Microsoft Transaction Server ' This code is in a code module.
Data Binding In Visual Basic Public Type udtMyType ' Definition of a Public UDT
birthDate As Date
Remoting Features of Visual Basic lastName As String
firstName As String
DHTML and Visual Basic Data Access address As String
End Type

Public Function passUDT(myrec As udtMyType) As udtMyType


' Modify the data somehow.
passUDT = myrec ' Return the UDT.
End Function

While code on the client machine that calls the function would be:

Option Explicit
Private myrec As udtMyType

Private Sub Command1_Click()


Dim x As udtMyType
x = passUDT(myrec)
' Do something with the UDT data.
End Sub

Passing a UDT as a Parameter of a Public Sub


While passing parameters has always been possible in previous versions of Visual Basic, passing user-defined types (UDTs) as parameters of public subs has not. This is now possible, as shown
in the example above.

Performance Considerations
The cost of passing parameters out-of-process is far higher than passing them in-process. When passing a parameter, the data must be marshaled and passed to the external process. The
code to accomplish this action can be expensive, but Visual Basic conceals this cost. The advantage of remoting data, however, is to create code that is easily comprehensible. Depending on
the size of the UDT, it may also be easier to maintain than an ADO Recordset object.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRemotingFeaturesOfVisualBasic.asp (1 of 2) [11/17/2002 11:03:44 PM]


Welcome to the MSDN Library
For More Information For details about creating and using UDTs, see Creating Your Own Data Types.

Remoting ADO Recordsets


ADO Recordset objects can also be remoted. With this capability, ADO recordsets are especially suited for use on intranet and Internet client-server applications. For example, you can create
an HTML or DHTML page that accesses data across the Internet from a web server application. When creating the HTML page, you can include the Microsoft ActiveX Data Access Recordset 2.0
Library, which features only the Recordset object. Since that library doesn't include the Command, Connection, and Parameter objects, your application will have the smallest possible footprint
while retaining the functionality of the ADO Recordset features. The code below shows an example of remoting ADO recordsets.

' This code is in a code module.


' Set a reference to the Microsoft ActiveX Data Objects 2.0 Library
Private MyADORecordset As ADODB.Recordset

Public Function GetCustomer(LastName As String) As ADODB.Recordset


' Query the DB
MyADORecordset.Open "SELECT * FROM Customers WHERE " & _
"LastName = '" & LastName & "'", cn, adOpenForwardOnly, adLockReadOnly
Set MyADORecordset.ActiveConnection = Nothing
Set GetCustomer = MyADORecordset ' Return the recordset.
End Function

While code on the client machine that calls the function would be:

Option Explicit
Private SomeServer As Object

Private Sub Command1_Click()


' Client can use the lighter ADOR library. Set a reference to
' the Microsoft ActiveX Data Objects Recordset 2.0 Library.
Dim MyData As ADOR.Recordset
Set SomeServer = CreateObject("foo.bar", myserver)
Set MyData = SomeServer.GetCustomer("Smith")
' Do something with the data.
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRemotingFeaturesOfVisualBasic.asp (2 of 2) [11/17/2002 11:03:44 PM]


DHTML and Visual Basic Data Access

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

Visual Basic Concepts

DHTML and Visual Basic Data Access

See Also

Using Visual Basic 6.0, you can now create data sources and data consumers, and all of the objects you create can be used as part of an intranet or Internet solution. For example, using the ADO
Recordset object with a data-aware class, you can create a data control that can be distributed as part of a web page created with the DHMTL Page Designer or the WebClass Designer.

IIS Applications and DHTML Applications

Both client- (DHTML) and server-based Internet applications (IIS) can interact with all Visual Basic data features. On the server side, you can use a webclass to open database connections in
response to an HTTP request, retrieve recordsets, and return them to the user. On the client side, you can create HTML elements on a page and bind them to data sources.

For details about using databases with IIS applications, see Using Databases with Webclasses. For information about creating a DHTML application that accesses data, see Creating a DHTML
Application that Interacts with SQL Server Data.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconDHTMLVisualBasicDataAccess.asp?frame=true [11/17/2002 11:03:49 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

DHTML and Visual Basic Data Access

See Also

Up One Level Using Visual Basic 6.0, you can now create data sources and data consumers, and all of the objects you create can be used as part of an intranet or Internet solution. For example, using the
ADO Recordset object with a data-aware class, you can create a data control that can be distributed as part of a web page created with the DHMTL Page Designer or the WebClass Designer.
Forms and Data-Aware Controls
ADO, DAO, and RDO in Visual Basic
OLE DB Providers IIS Applications and DHTML Applications
Visual Basic Data Sources
Both client- (DHTML) and server-based Internet applications (IIS) can interact with all Visual Basic data features. On the server side, you can use a webclass to open database connections in
Visual Basic and Microsoft Transaction Server response to an HTTP request, retrieve recordsets, and return them to the user. On the client side, you can create HTML elements on a page and bind them to data sources.

Data Binding In Visual Basic


Remoting Features of Visual Basic For details about using databases with IIS applications, see Using Databases with Webclasses. For information about creating a DHTML application that accesses data, see Creating a DHTML
Application that Interacts with SQL Server Data.
DHTML and Visual Basic Data Access

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDHTMLVisualBasicDataAccess.asp [11/17/2002 11:03:50 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)

MSDN Library GO
Advanced Search Visual Basic Concepts

Data Access Tools in Visual Basic

See Also

Up One Level Visual Basic provides a number of tools to meet data access programming needs, such as controls and data-bound controls, designers, and technologies such as Format objects. This chapter
introduces the tools listed below.
The Data View Window and Visual Database Tools
Format Objects Topics
The SQL Editor
Stored Procedures in the SQL Editor ● DataView Window and the Microsoft Visual Database tools: Database Designer and Query Designer.

Data Environment Designer


Triggers in the SQL Editor

● Data Report Designer

The T-SQL Debugger ● Format Objects

The UserConnection Designer ● The SQL Editor

Wizards Related to Data Access


● T-SQL Debugger

● Wizards Related to Data Access

● UserConnection Designer This ActiveX designer is used for RDO programming.

Other Data Access Subjects

For information on controls related to data access, see the Programmer's Guide:

● Using the ADO Data Control

● Using the DataCombo and DataList Controls

● Using the DataGrid Control

● Using the Microsoft FlexGrid and Hierarchical FlexGrid Controls

For information on data binding, see Building Data Sources.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDataAccessToolsInVisualBasic.asp [11/17/2002 11:03:59 PM]


The Data View Window and Visual Database Tools

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

Visual Basic Concepts

The Data View Window and Visual Database Tools

See Also

The Data View window presents a view onto one or more database connections, providing access to the entire structure of the database on a particular connection. The Data View window provides
the means to use the Microsoft Visual Database Tools (Query Designer and Database Designer) to visually manipulate that structure of a database.

To open the Data View window, click Data View on the View menu, or click the Data View button on the Standard toolbar.

Click the jumps below to see detailed discussions of the Data View window and its related tools.

● Managing Databases in Data View

● Introducing Microsoft Visual Database Tools

● Database Designer

● Query Designer

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconTheDataViewWindow.asp?frame=true [11/17/2002 11:04:02 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

The Data View Window and Visual Database Tools

See Also

Up One Level The Data View window presents a view onto one or more database connections, providing access to the entire structure of the database on a particular connection. The Data View window
provides the means to use the Microsoft Visual Database Tools (Query Designer and Database Designer) to visually manipulate that structure of a database.
The Data View Window and Visual Database Tools
Format Objects To open the Data View window, click Data View on the View menu, or click the Data View button on the Standard toolbar.
The SQL Editor
Stored Procedures in the SQL Editor Click the jumps below to see detailed discussions of the Data View window and its related tools.
Triggers in the SQL Editor
The T-SQL Debugger ● Managing Databases in Data View

The UserConnection Designer ● Introducing Microsoft Visual Database Tools

Database Designer
Wizards Related to Data Access

● Query Designer

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconTheDataViewWindow.asp [11/17/2002 11:04:04 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Format Objects

See Also

Up One Level Format objects allow you to format and unformat data passed between a database and a bound object. You can also use the traditional Format function to format your data, but format objects
offer these advantages:
Format Objects Tutorial
● The Format and Unformat events allow closer control over data formatting.

● You can set formats either through code or using the IDE; in either case when you use format objects you'll write less code.

● Format objects give you more formatting types.

Types of formatting available from format objects include the standard types supported by the Format function (currency, date/time, string) plus the types in the following table.

Formatting option Description

Boolean Specifies values displayed in the bound control when data read from the database is a Boolean true or false. Writes a Boolean true or false to the database when the data matches a specified value.

Binary Allows any binary data to be read from and written to the database.

Object Allows an object to be read from and written to the database.

Picture Allows a picture to be read from and written to the database.

Checkbox Values read from the database will determine the Value property for a checkbox. Checkbox Value property settings will determine true/false values written to the database.

Stepping Through the Process

You can set formatting options in code or using property pages available from the bound control's DataFormat property in the property window. When the bound control fetches a record from
the database, formatting is applied according to properties of the StdDataFormat object, then the Format event is fired and data is displayed by the bound control.

When data is written back to the database, the formatting you applied goes with it. In most cases this works fine, but if you use the Format property to apply complex formatting you may
create strings your database cannot unformat. In these cases you need to unformat the data in the Unformat event before it is written to the database.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingFormatObjects.asp (1 of 2) [11/17/2002 11:04:08 PM]


Welcome to the MSDN Library

Understanding the Object Hierarchy

Format objects include:

● StdDataFormat object

This object provides the Format and Unformat events, and it lets you select format types and apply format strings.

● StdDataFormats collection

Complex bound controls will usually need more than one StdDataFormat object. In this case the StdDataFormats collection gives you top-level access to the collection.

● DataValue object

You can use the DataValue object in the Format and Unformat events to customize formatting beyond what is provided by the StdDataFormat object.

● DataFormat property

The DataFormat property of the bound control sets or returns the StdDataFormat object.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingFormatObjects.asp (2 of 2) [11/17/2002 11:04:08 PM]


Format Objects Tutorial

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic > Format Objects

Visual Basic Concepts

Format Objects Tutorial

See Also

The following procedure gives you a brief overview of using format objects with bound controls attached to the ADO Data Control. The example uses the Nwind.mdb sample database provided with
Visual Basic.

Note that although this example uses the ADO Data Control, format objects can be used with any data source.

Using the ADO Data Control with Format Objects

1. Create an OLEDB Data Source for the Northwind database, named "Northwind".

If a data source has not been created, follow the steps in Creating the Northwind OLEDB Data Source.

2. From the Project menu, set references to the Microsoft Data Formatting Object Library and the Microsoft Data Binding Collection.

3. On the Project menu click Components, and check the ADO Data Control.

4. Add the ADO Data control and three TextBox controls to a form.

5. Set property values as shown in the following table.

Object Property Setting

ADO control ConnectionString northwind.udl


(Use Data Link File)

ADO control RecordSource select * from Employees

Text1 control DataSource ADODC1

Text1 control DataField LastName

Text2 control DataSource ADODC1

Text2 control DataField HireDate

Text3 control DataSource ADODC1

Text3 control DataField Extension

6. Add the following declarations to the form.

' Binds textboxes to the ADO control.


Dim bc As New BindingCollection

' We'll add code to the Format event on this object.


Dim WithEvents f1 as StdDataFormat
Dim WithEvents f2 As StdDataFormat

Declaring f2 with the WithEvents statement exposes the object's events. Step 8 shows code using the Format event to work on data as it is passed back and forth between the database and bound object.

7. Add the following code to the form's Load event.

' Connect the BindingCollection object to the datasource.


Set bc.DataSource = ADODC1

'set a long date format string


Set f1 = New StdDataFormat
f1.Type = fmtCustom
f1.Format = "long date"
' Use the BindingCollection object to bind the 2nd text box.
bc.Add Text2, "text", "hiredate", f1

'set a currency format string


Set f2 = New StdDataFormat
f2.Type = fmtCustom
f2.Format = "$0.00"
' Use the BindingCollection object to bind the 3rd text box.
Set bc.DataSource = ADODC1
bc.Add Text3, "text", "extension", f2

8. Add the following code to the f2 object's Format event.

If DataValue.Value < 3000 Then


Text3.ForeColor = vbRed
Else
Text3.ForeColor = vbBlack
End If

9. Run the project and experiment with the ADO Data control.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconFormatObjectsTutorial.asp?frame=true (1 of 2) [11/17/2002 11:04:11 PM]


Format Objects Tutorial

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconFormatObjectsTutorial.asp?frame=true (2 of 2) [11/17/2002 11:04:11 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic > Format Objects

MSDN Library GO
Advanced Search Visual Basic Concepts

Format Objects Tutorial

See Also

Up One Level The following procedure gives you a brief overview of using format objects with bound controls attached to the ADO Data Control. The example uses the Nwind.mdb sample database provided
with Visual Basic.
Format Objects Tutorial
Note that although this example uses the ADO Data Control, format objects can be used with any data source.

Using the ADO Data Control with Format Objects

1. Create an OLEDB Data Source for the Northwind database, named "Northwind".

If a data source has not been created, follow the steps in Creating the Northwind OLEDB Data Source.

2. From the Project menu, set references to the Microsoft Data Formatting Object Library and the Microsoft Data Binding Collection.

3. On the Project menu click Components, and check the ADO Data Control.

4. Add the ADO Data control and three TextBox controls to a form.

5. Set property values as shown in the following table.

Object Property Setting

ADO control ConnectionString northwind.udl


(Use Data Link File)

ADO control RecordSource select * from Employees

Text1 control DataSource ADODC1

Text1 control DataField LastName

Text2 control DataSource ADODC1

Text2 control DataField HireDate

Text3 control DataSource ADODC1

Text3 control DataField Extension

6. Add the following declarations to the form.

' Binds textboxes to the ADO control.


Dim bc As New BindingCollection

' We'll add code to the Format event on this object.


Dim WithEvents f1 as StdDataFormat
Dim WithEvents f2 As StdDataFormat

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconFormatObjectsTutorial.asp (1 of 2) [11/17/2002 11:04:13 PM]


Welcome to the MSDN Library
Declaring f2 with the WithEvents statement exposes the object's events. Step 8 shows code using the Format event to work on data as it is passed back and forth between the database and bound object.

7. Add the following code to the form's Load event.

' Connect the BindingCollection object to the datasource.


Set bc.DataSource = ADODC1

'set a long date format string


Set f1 = New StdDataFormat
f1.Type = fmtCustom
f1.Format = "long date"
' Use the BindingCollection object to bind the 2nd text box.
bc.Add Text2, "text", "hiredate", f1

'set a currency format string


Set f2 = New StdDataFormat
f2.Type = fmtCustom
f2.Format = "$0.00"
' Use the BindingCollection object to bind the 3rd text box.
Set bc.DataSource = ADODC1
bc.Add Text3, "text", "extension", f2

8. Add the following code to the f2 object's Format event.

If DataValue.Value < 3000 Then


Text3.ForeColor = vbRed
Else
Text3.ForeColor = vbBlack
End If

9. Run the project and experiment with the ADO Data control.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconFormatObjectsTutorial.asp (2 of 2) [11/17/2002 11:04:13 PM]


The SQL Editor

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

Visual Basic Concepts

The SQL Editor

See Also

The SQL Editor allows you to create and edit stored procedures and triggers in both SQL Server and Oracle from within the Visual Basic development environment. The topics listed below give you
an overview of using the SQL Editor.

Stored Procedures in the SQL Editor

Triggers in the SQL Editor

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconSQLEditor.asp?frame=true [11/17/2002 11:04:18 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

The SQL Editor

See Also

Up One Level The SQL Editor allows you to create and edit stored procedures and triggers in both SQL Server and Oracle from within the Visual Basic development environment. The topics listed below give
you an overview of using the SQL Editor.
The Data View Window and Visual Database Tools
Format Objects Stored Procedures in the SQL Editor
The SQL Editor
Stored Procedures in the SQL Editor
Triggers in the SQL Editor
Triggers in the SQL Editor
The T-SQL Debugger
The UserConnection Designer
Wizards Related to Data Access Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconSQLEditor.asp [11/17/2002 11:04:20 PM]


Stored Procedures in the SQL Editor

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

Visual Basic Concepts

Stored Procedures in the SQL Editor

See Also

Stored procedures enable you to manage your server-based database and display information about that database and its users. For example, you can use a stored procedure to display the title
(from the titles table) and publisher (from the publishers table) for each author in the authors table.

Stored procedures can contain program flow, logic, and queries against the database. They can accept parameters, generate parameters, return single or multiple result sets, and return values.

You can use stored procedures for any purpose for which you would use SQL statements, with these advantages:

● You can execute a series of SQL statements in a single stored procedure.

● You can reference other stored procedures from within your stored procedure, which can simplify a series of complex statements.

● The stored procedure is compiled on the server when it is created, so it executes faster than individual SQL statements.

● The compiled stored procedure can be cached in memory as well, for faster execution.

Creating New Stored Procedures


The SQL editor can be opened from the Data View window. The Data View window can be opened from the View menu or the Standard toolbar.

To create a new stored procedure

1. In Data View, right-click the Stored Procedures folder or any stored procedure in that folder.

2. Choose New Stored Procedure from the shortcut menu.

A new stored procedure is created using a template containing SQL statements.

3. Replace StoredProcedure in the first line with the name of the procedure. For example, you might use "MyProcedure" as the name:

Create Procedure MyProcedure

Note Stored procedures must have unique names. If you choose a name that is already assigned to another stored procedure in your project, an error message is displayed.

4. Write the remaining procedure text in SQL.

For more information and examples of stored procedures, see the documentation for your server. If you are using Microsoft® SQL Server™, see the "CREATE PROCEDURE" statement in the SQL
Server documentation. The Visual Basic SQL Editor also works with Oracle Stored Procedures, Functions, and Packages.

Running Stored Procedures


You can run a stored procedure against your database to execute the SQL statements it contains and display the results in the Immediate window.

To run a stored procedure

1. In Data View, expand the Stored Procedures folder.

2. Right-click the name of the stored procedure that you want to run. Choose Run from the shortcut menu.

3. If any parameters are required, a dialog appears to enter the parameter values.

Copying Stored Procedures


You can copy a stored procedure as the first step in creating a new stored procedure for your database. Because stored procedures must have names that are unique, the new stored procedure is
automatically assigned a new unique name based on the original name.

To copy a stored procedure

1. In Data View, expand the Stored Procedures folder.

2. Right-click the name of the stored procedure that you want to copy. Choose Design from the shortcut menu.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconStoredProcSQLEditor.asp?frame=true (1 of 2) [11/17/2002 11:04:24 PM]


Stored Procedures in the SQL Editor
The SQL Editor opens with the stored procedure.

3. Select all the text in the SQL Editor.

4. Right-click the SQL Editor. Choose Copy from the shortcut menu.

5. Right-click the SQL Editor. Choose New Stored Procedure Wizard from the shortcut menu.

6. Clear the template text.

7. Right-click the SQL Editor. Choose Paste from the shortcut menu to create your new stored procedure.

8. Change the name of the stored procedure.

9. Save the stored procedure to the database.

You can edit the SQL statements in the new stored procedure.

Setting Execution Permissions on Stored Procedures


You can set execute permissions for a stored procedure that you own to allow access to the stored procedure by specific users or groups. In many databases, such as Microsoft® SQL Server™ and
Oracle Database Server, if you are not the database owner, then you must explicitly grant permissions for your stored procedure to other users. Use SQL Server’s ISQL utility, Enterprise Manager,
or an Oracle Tool to run the change commands or visually set the permissions.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconStoredProcSQLEditor.asp?frame=true (2 of 2) [11/17/2002 11:04:24 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Stored Procedures in the SQL Editor

See Also

Up One Level Stored procedures enable you to manage your server-based database and display information about that database and its users. For example, you can use a stored procedure to display the
title (from the titles table) and publisher (from the publishers table) for each author in the authors table.
The Data View Window and Visual Database Tools
Format Objects Stored procedures can contain program flow, logic, and queries against the database. They can accept parameters, generate parameters, return single or multiple result sets, and return
The SQL Editor values.

Stored Procedures in the SQL Editor


Triggers in the SQL Editor You can use stored procedures for any purpose for which you would use SQL statements, with these advantages:

The T-SQL Debugger


The UserConnection Designer ●


You can execute a series of SQL statements in a single stored procedure.

You can reference other stored procedures from within your stored procedure, which can simplify a series of complex statements.

Wizards Related to Data Access ● The stored procedure is compiled on the server when it is created, so it executes faster than individual SQL statements.

● The compiled stored procedure can be cached in memory as well, for faster execution.

Creating New Stored Procedures


The SQL editor can be opened from the Data View window. The Data View window can be opened from the View menu or the Standard toolbar.

To create a new stored procedure

1. In Data View, right-click the Stored Procedures folder or any stored procedure in that folder.

2. Choose New Stored Procedure from the shortcut menu.

A new stored procedure is created using a template containing SQL statements.

3. Replace StoredProcedure in the first line with the name of the procedure. For example, you might use "MyProcedure" as the name:

Create Procedure MyProcedure

Note Stored procedures must have unique names. If you choose a name that is already assigned to another stored procedure in your project, an error message is displayed.

4. Write the remaining procedure text in SQL.

For more information and examples of stored procedures, see the documentation for your server. If you are using Microsoft® SQL Server™, see the "CREATE PROCEDURE" statement in the
SQL Server documentation. The Visual Basic SQL Editor also works with Oracle Stored Procedures, Functions, and Packages.

Running Stored Procedures


You can run a stored procedure against your database to execute the SQL statements it contains and display the results in the Immediate window.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconStoredProcSQLEditor.asp (1 of 2) [11/17/2002 11:04:26 PM]


Welcome to the MSDN Library
To run a stored procedure

1. In Data View, expand the Stored Procedures folder.

2. Right-click the name of the stored procedure that you want to run. Choose Run from the shortcut menu.

3. If any parameters are required, a dialog appears to enter the parameter values.

Copying Stored Procedures


You can copy a stored procedure as the first step in creating a new stored procedure for your database. Because stored procedures must have names that are unique, the new stored
procedure is automatically assigned a new unique name based on the original name.

To copy a stored procedure

1. In Data View, expand the Stored Procedures folder.

2. Right-click the name of the stored procedure that you want to copy. Choose Design from the shortcut menu.

The SQL Editor opens with the stored procedure.

3. Select all the text in the SQL Editor.

4. Right-click the SQL Editor. Choose Copy from the shortcut menu.

5. Right-click the SQL Editor. Choose New Stored Procedure Wizard from the shortcut menu.

6. Clear the template text.

7. Right-click the SQL Editor. Choose Paste from the shortcut menu to create your new stored procedure.

8. Change the name of the stored procedure.

9. Save the stored procedure to the database.

You can edit the SQL statements in the new stored procedure.

Setting Execution Permissions on Stored Procedures


You can set execute permissions for a stored procedure that you own to allow access to the stored procedure by specific users or groups. In many databases, such as Microsoft® SQL Server™
and Oracle Database Server, if you are not the database owner, then you must explicitly grant permissions for your stored procedure to other users. Use SQL Server’s ISQL utility, Enterprise
Manager, or an Oracle Tool to run the change commands or visually set the permissions.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconStoredProcSQLEditor.asp (2 of 2) [11/17/2002 11:04:26 PM]


Triggers in the SQL Editor

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

Visual Basic Concepts

Triggers in the SQL Editor

See Also

A trigger is a special kind of stored procedure that goes into effect when you modify data in a specified table using one or more data modification operations: UPDATE, INSERT, or DELETE. Triggers
can query other tables and can include complex SQL statements. They are primarily useful for enforcing complex business rules or requirements. For example, you could control whether to allow
an order to be inserted based on a customer's current account status.

Triggers are also useful for enforcing referential integrity, which preserves the defined relationships between tables when you add, update, or delete the rows in those tables. However, the best
way to enforce referential integrity is to define primary key and foreign key constraints in the related tables. If you use database diagrams, you can create a relationship between tables to
automatically create a foreign key constraint.

Advantages of Using Triggers


Triggers are useful in these ways:

● Triggers are automatic: they are activated immediately after any modification to the table's data, such as a manual entry or an application action.

● Triggers can cascade changes through related tables in the database. For example, you can write a delete trigger on the title_id column of the titles table to cause a deletion of matching rows in other tables. The trigger uses the title_id column as a unique
key to locate matching rows in the titleauthor, sales, and roysched tables.

● Triggers can enforce restrictions that are more complex than those defined with check constraints. Unlike check constraints, triggers can reference columns in other tables. For example, a trigger can roll back updates that attempt to apply a discount (stored in the
discounts table) to books (stored in the titles table) with a price of less than $10.

Creating a Trigger
A trigger is a database object that you create by specifying:

● The current table.

● The data modification transactions that activate the trigger: adding new data (INSERT), updating existing data (UPDATE), or deleting existing data (DELETE).

● The actions that the trigger will take immediately following the transactions you specified.

You write triggers in Transact-SQL for Microsoft® SQL Server™ databases or PL/SQL for Oracle databases.

To create a trigger

1. In Data View (available from the Standard toolbar or the View menu), expand the Tables folder.

2. Right-click the name of the table that you want to create a trigger on. Choose New Trigger from the shortcut menu.

A new trigger is created with the following SQL statements already defined for you:

Create Trigger /*Trigger_Name*/


on /*Table_name*/
For /*Insert, Update, Delete*/
As
print 'Trigger Fired'

3. Modify the trigger text as follows:

Line Replace With

1 /*Trigger_Name*/ The name you want to assign to the trigger

2 /*Table_name*/ The name of the table you want to attach the trigger to

3 /*Insert, Update, Delete*/ The type of transactions that will activate this trigger

For example, to create a trigger named employee_insupd for insert and update transactions on the employee table, you would change the first three lines of the trigger text to the following:

Create Trigger employee_insupd


on employee
For Insert, Update

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconTriggersSQLEditor.asp?frame=true (1 of 2) [11/17/2002 11:04:31 PM]


Triggers in the SQL Editor

4. Write the remaining trigger text in SQL.

For examples of triggers for Microsoft SQL Server databases, see "Creating a Trigger" in the SQL Server documentation. For details about the Transact-SQL syntax of triggers, see the "CREATE
TRIGGER" statement in the SQL Server documentation.

Opening a Trigger
You can open a trigger to view or edit the text of an existing trigger that is stored in your database. Triggers are scripted in Transact-SQL for Microsoft® SQL Server™ databases or PL/SQL for
Oracle databases.

To open a trigger

1. In Data View, expand the Tables folder.

2. Expand the table whose trigger you want to open.

3. Right-click the name of the trigger that you want to open and click Design on the shortcut menu.

-or-

Double-click the name of the trigger that you want to open.

Saving a Trigger
To add a new trigger to the database or to update an existing trigger that you have modified, you can save a trigger.

To save a trigger

1. In the SQL Editor, choose Save to Database from the File menu.

2. If you are updating an existing trigger, a message box prompts you to confirm the save action. Choose Yes.

A saved trigger appears in the Tables folder in Data View under the table that it's attached to.

Deleting a Trigger
To disable the actions defined in the trigger that are automatically carried out on your database immediately following the specified transactions, you can delete a trigger.

You might also want to delete any triggers that enforce referential integrity between related tables if you use database diagrams to design your database. Database diagrams use relationships
instead of triggers for this purpose. Thus, if a trigger duplicates a relationship in a database diagram, you should delete either the trigger or the relationship.

To delete a trigger

1. In Data View, expand the Tables folder.

2. Expand the table whose trigger you want to delete.

3. Right-click the trigger that you want to delete and choose Delete from the shortcut menu.

4. A message prompts you to confirm the deletion. Choose Yes.

The trigger is deleted from the database and Data View.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconTriggersSQLEditor.asp?frame=true (2 of 2) [11/17/2002 11:04:31 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Triggers in the SQL Editor

See Also

Up One Level A trigger is a special kind of stored procedure that goes into effect when you modify data in a specified table using one or more data modification operations: UPDATE, INSERT, or DELETE.
Triggers can query other tables and can include complex SQL statements. They are primarily useful for enforcing complex business rules or requirements. For example, you could control
The Data View Window and Visual Database Tools whether to allow an order to be inserted based on a customer's current account status.

Format Objects
The SQL Editor Triggers are also useful for enforcing referential integrity, which preserves the defined relationships between tables when you add, update, or delete the rows in those tables. However, the best
way to enforce referential integrity is to define primary key and foreign key constraints in the related tables. If you use database diagrams, you can create a relationship between tables to
Stored Procedures in the SQL Editor automatically create a foreign key constraint.

Triggers in the SQL Editor


The T-SQL Debugger
Advantages of Using Triggers
The UserConnection Designer
Wizards Related to Data Access Triggers are useful in these ways:

● Triggers are automatic: they are activated immediately after any modification to the table's data, such as a manual entry or an application action.

● Triggers can cascade changes through related tables in the database. For example, you can write a delete trigger on the title_id column of the titles table to cause a deletion of matching rows in other tables. The trigger uses the title_id column as a
unique key to locate matching rows in the titleauthor, sales, and roysched tables.

● Triggers can enforce restrictions that are more complex than those defined with check constraints. Unlike check constraints, triggers can reference columns in other tables. For example, a trigger can roll back updates that attempt to apply a discount (stored
in the discounts table) to books (stored in the titles table) with a price of less than $10.

Creating a Trigger
A trigger is a database object that you create by specifying:

● The current table.

● The data modification transactions that activate the trigger: adding new data (INSERT), updating existing data (UPDATE), or deleting existing data (DELETE).

● The actions that the trigger will take immediately following the transactions you specified.

You write triggers in Transact-SQL for Microsoft® SQL Server™ databases or PL/SQL for Oracle databases.

To create a trigger

1. In Data View (available from the Standard toolbar or the View menu), expand the Tables folder.

2. Right-click the name of the table that you want to create a trigger on. Choose New Trigger from the shortcut menu.

A new trigger is created with the following SQL statements already defined for you:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconTriggersSQLEditor.asp (1 of 3) [11/17/2002 11:04:34 PM]


Welcome to the MSDN Library
Create Trigger /*Trigger_Name*/
on /*Table_name*/
For /*Insert, Update, Delete*/
As
print 'Trigger Fired'

3. Modify the trigger text as follows:

Line Replace With

1 /*Trigger_Name*/ The name you want to assign to the trigger

2 /*Table_name*/ The name of the table you want to attach the trigger to

3 /*Insert, Update, Delete*/ The type of transactions that will activate this trigger

For example, to create a trigger named employee_insupd for insert and update transactions on the employee table, you would change the first three lines of the trigger text to the following:

Create Trigger employee_insupd


on employee
For Insert, Update

4. Write the remaining trigger text in SQL.

For examples of triggers for Microsoft SQL Server databases, see "Creating a Trigger" in the SQL Server documentation. For details about the Transact-SQL syntax of triggers, see the "CREATE
TRIGGER" statement in the SQL Server documentation.

Opening a Trigger
You can open a trigger to view or edit the text of an existing trigger that is stored in your database. Triggers are scripted in Transact-SQL for Microsoft® SQL Server™ databases or PL/SQL for
Oracle databases.

To open a trigger

1. In Data View, expand the Tables folder.

2. Expand the table whose trigger you want to open.

3. Right-click the name of the trigger that you want to open and click Design on the shortcut menu.

-or-

Double-click the name of the trigger that you want to open.

Saving a Trigger
To add a new trigger to the database or to update an existing trigger that you have modified, you can save a trigger.

To save a trigger

1. In the SQL Editor, choose Save to Database from the File menu.

2. If you are updating an existing trigger, a message box prompts you to confirm the save action. Choose Yes.

A saved trigger appears in the Tables folder in Data View under the table that it's attached to.

Deleting a Trigger
To disable the actions defined in the trigger that are automatically carried out on your database immediately following the specified transactions, you can delete a trigger.

You might also want to delete any triggers that enforce referential integrity between related tables if you use database diagrams to design your database. Database diagrams use relationships
instead of triggers for this purpose. Thus, if a trigger duplicates a relationship in a database diagram, you should delete either the trigger or the relationship.

To delete a trigger

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconTriggersSQLEditor.asp (2 of 3) [11/17/2002 11:04:34 PM]


Welcome to the MSDN Library
1. In Data View, expand the Tables folder.

2. Expand the table whose trigger you want to delete.

3. Right-click the trigger that you want to delete and choose Delete from the shortcut menu.

4. A message prompts you to confirm the deletion. Choose Yes.

The trigger is deleted from the database and Data View.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconTriggersSQLEditor.asp (3 of 3) [11/17/2002 11:04:34 PM]


The T-SQL Debugger

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

Visual Basic Concepts

The T-SQL Debugger

See Also

The T-SQL debugger is integrated with the Data Environment designer. It allows you to interactively debug remote stored procedures written in Microsoft SQL Server's Transact SQL dialect, from
within the Visual Basic development environment. Using the T-SQL debugger, you can:

● Display the SQL call stack, local variables, and parameters for the SQL stored procedure.

● Control and manage breakpoints.

● View and modify local variables and parameters.

● View global variables.

Setup and Compatibility

In order to use the T-SQL debugger, you must have SQL Server version 6.5 with Service Pack 3 or later installed as your database server. The debugger uses the functionality exposed by SQL
Server's Sdi.dll, and exposes that functionality through Remote Automation.

The client-side components of the T-SQL debugger are correctly installed and configured when you choose to install all the Enterprise tools in your Visual Basic installation. If it is necessary to
repeat the setup process, select "Custom" from the CD Installation dialog box, and choose "Select All" for the Enterprise Tools selection.

Server-Side Setup
With SQL Server version 6.5 and Service Pack 3 or later installed, you can install and register the SQL Debugger interface and Remote Automation component on the server. These components are
located at \Program files\Common Files\Microsoft Shared\SQL Debugging. On Windows NT 4.0 or later, simply run the setup program Sdi_nt4.exe.

Note For setup on NT Server 3.51, you must manually copy and register the necessary files. Complete instructions for this process are included in the Readme.txt file in the \Program
Files\Common Files\Microsoft Shared\SQL Debugging folder.

Using the T-SQL Debugger

There are different methods you can use to invoke T-SQL debugging.

1. To debug a stored procedure or batch query at design time, add the T-SQL Debugger Add-In via Visual Basic's Add-In Manager (on the Add-Ins menu). Then you can start the add-in by clicking T-SQL Debugger on the Add-Ins menu. You then simply select a
DSN, and either Stored Procedure or Batch SQL and click the Execute button. This will invoke the debugger and allow you to debug the SQL you are interested in.

2. To debug stored procedures while debugging Visual Basic code (run-time debugging), select T-SQL Debugging Options on Visual Basic's Tools menu. The options dialog box allows you to:
● Turn on automatic step into stored procedures, which will bring up the T-SQL Debugger whenever you step into an ADO or RDO method that executes a stored procedure.

● Turn Safe Mode on, which will automatically roll back any design-time queries that you debug.

● Limit the number of rows that appear in the T-SQL Debugger output window when debugging design time queries.

● Set the login timeout value that the debugger uses to connect to the database, to get internal SQL State.

Once you have selected the Automatically step into Stored Procedures check box, if you step into (F8) a line of code that executes an ADO or RDO method that invokes a stored procedure, the debugger will automatically be started. You can then step through
the stored procedure and then continue debugging your Visual Basic code.

Note SQL Server will return from a stored procedure before it has finished executing if the stored procedure returns enough data to fill its buffers. If this happens, both the T-SQL Debugger and the Visual Basic debugger will be active at the same time. Your
Visual Basic code must fetch the results from ADO or RDO before the stored procedure will complete its execution. If this happens, make sure your basic code reads the result sets by placing Visual Basic in Run Mode (F5) and setting breakpoints where you would
like to stop execution. You can toggle back and forth between Visual Basic and the T-SQL Debugger by using the taskbar or using the ALT+TAB key combination.

3. You can also launch the T-SQL Debugger:


● From the Data Environment designer

● While stepping through ADO or RDO code

● By right-clicking a stored procedure in the Data View window and choosing the Debug command

● From the UserConnection designer

Once you have started the debugger, it establishes the ODBC connection and displays the Enter Unassigned Parameters dialog box, as shown.

Unassigned Parameters Dialog box

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconTheTSQLDebugger.asp?frame=true (1 of 3) [11/17/2002 11:04:39 PM]


The T-SQL Debugger

Enter values for any unassigned parameters in the Value field, then click OK. The T-SQL debugger interface appears and displays the text of the stored procedure:

T-SQL Debugger Interface

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconTheTSQLDebugger.asp?frame=true (2 of 3) [11/17/2002 11:04:39 PM]


The T-SQL Debugger

Debugging Options

With the SQL statement displayed, several debugging options are available on the toolbar buttons and on the Debug menu. These options include:

● 2Go

● Set and clear breakpoints

● Step

● Step into subexpression

● Step over subexpression

● Run to cursor

● Stop debugging

● Restart

Views and Options


In addition to the code window containing the SQL statement you are debugging, the T-SQL debugger interface presents separate output windows for local and global variables, and for the output
(result set) of the query. The View menu also allows you to open a separate Call Stack window and a Temp Table Dump window, so that you can examine these as the code executes.

The Options menu lets you customize the appearance of the T-SQL debugger by changing the fonts and colors used for display.

Exiting from the T-SQL Debugger

When you are finished with your debugging session, click Exit on the File menu to close the debugger. To execute a query again, click Restart on the Debug menu.

Troubleshooting

If you are having problems getting T-SQL debugging to work, you will need to check the event log on the server. SDI.DLL will log events in the application section of the event viewer. COM or
distributed COM errors will log events in the system section of the viewer.

● Make sure that the two computers can communicate with each other. The easiest mechanism to do this is by typing ping and the computer name of the client at a command prompt on the server if you are running TCP/IP. If this fails, fix the connectivity problem
between the machines.

● Make sure the file SDI.DLL resides in the same directory as SQLSERVR.EXE. This will be in the binn sub-directory under the main SQL Server directory. The default is c:\mssql\binn.

● Ensure that the RPC services are started on the server machine. You do this by starting the control panel, opening the services application and checking that the Remote Procedure Call ( RPC ) Service is running and set to start automatically, as well as the Remote
Procedure Call ( RPC ) Locator.

● Ensure that SQL Server is not set to log on as the SystemAccount. You do this by starting the control panel, opening the services application and double clicking on the MSSQLServer service. If the service is set to run as the SystemAccount, change this so the
server will log on to a specific account that is valid to the domain that you are in. If debugging still fails, make sure that the account SQL Server started as has sufficient rights to launch an automation server on the client machine.

● If you see COM error 80080005 in the event log, make sure that you did not start remote automation (autmgr32) from the command prompt. Autmgr32.exe should only be running in the winstation of the account that SQL Server logged in as. Any other winstation
will cause problems. If this is the case, close down autmgr32.exe via the task manager and let the sdi.dll and autprx32.dll load autmgr32 via COM.

● Make sure Remote Automation is successfully installed on the server and client machines, if both the client and server do not have Distributed COM (DCOM) installed and loaded.

● If your client system is running Windows NT 4.0 or later, run DCOMCNFG and make sure that everyone has launch and access permission for vbsdicli.exe.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconTheTSQLDebugger.asp?frame=true (3 of 3) [11/17/2002 11:04:39 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

The T-SQL Debugger

See Also

Up One Level The T-SQL debugger is integrated with the Data Environment designer. It allows you to interactively debug remote stored procedures written in Microsoft SQL Server's Transact SQL dialect,
from within the Visual Basic development environment. Using the T-SQL debugger, you can:
The Data View Window and Visual Database Tools
Format Objects ● Display the SQL call stack, local variables, and parameters for the SQL stored procedure.

The SQL Editor ● Control and manage breakpoints.

View and modify local variables and parameters.


Stored Procedures in the SQL Editor

● View global variables.

Triggers in the SQL Editor


The T-SQL Debugger Setup and Compatibility

The UserConnection Designer


In order to use the T-SQL debugger, you must have SQL Server version 6.5 with Service Pack 3 or later installed as your database server. The debugger uses the functionality exposed by SQL
Wizards Related to Data Access Server's Sdi.dll, and exposes that functionality through Remote Automation.

The client-side components of the T-SQL debugger are correctly installed and configured when you choose to install all the Enterprise tools in your Visual Basic installation. If it is necessary to
repeat the setup process, select "Custom" from the CD Installation dialog box, and choose "Select All" for the Enterprise Tools selection.

Server-Side Setup
With SQL Server version 6.5 and Service Pack 3 or later installed, you can install and register the SQL Debugger interface and Remote Automation component on the server. These components
are located at \Program files\Common Files\Microsoft Shared\SQL Debugging. On Windows NT 4.0 or later, simply run the setup program Sdi_nt4.exe.

Note For setup on NT Server 3.51, you must manually copy and register the necessary files. Complete instructions for this process are included in the Readme.txt file in the \Program
Files\Common Files\Microsoft Shared\SQL Debugging folder.

Using the T-SQL Debugger

There are different methods you can use to invoke T-SQL debugging.

1. To debug a stored procedure or batch query at design time, add the T-SQL Debugger Add-In via Visual Basic's Add-In Manager (on the Add-Ins menu). Then you can start the add-in by clicking T-SQL Debugger on the Add-Ins menu. You then simply select
a DSN, and either Stored Procedure or Batch SQL and click the Execute button. This will invoke the debugger and allow you to debug the SQL you are interested in.

2. To debug stored procedures while debugging Visual Basic code (run-time debugging), select T-SQL Debugging Options on Visual Basic's Tools menu. The options dialog box allows you to:
● Turn on automatic step into stored procedures, which will bring up the T-SQL Debugger whenever you step into an ADO or RDO method that executes a stored procedure.

● Turn Safe Mode on, which will automatically roll back any design-time queries that you debug.

● Limit the number of rows that appear in the T-SQL Debugger output window when debugging design time queries.

● Set the login timeout value that the debugger uses to connect to the database, to get internal SQL State.

Once you have selected the Automatically step into Stored Procedures check box, if you step into (F8) a line of code that executes an ADO or RDO method that invokes a stored procedure, the debugger will automatically be started. You can then step
through the stored procedure and then continue debugging your Visual Basic code.

Note SQL Server will return from a stored procedure before it has finished executing if the stored procedure returns enough data to fill its buffers. If this happens, both the T-SQL Debugger and the Visual Basic debugger will be active at the same time. Your
Visual Basic code must fetch the results from ADO or RDO before the stored procedure will complete its execution. If this happens, make sure your basic code reads the result sets by placing Visual Basic in Run Mode (F5) and setting breakpoints where you
would like to stop execution. You can toggle back and forth between Visual Basic and the T-SQL Debugger by using the taskbar or using the ALT+TAB key combination.

3. You can also launch the T-SQL Debugger:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconTheTSQLDebugger.asp (1 of 4) [11/17/2002 11:04:42 PM]


Welcome to the MSDN Library
● From the Data Environment designer

● While stepping through ADO or RDO code

● By right-clicking a stored procedure in the Data View window and choosing the Debug command

● From the UserConnection designer

Once you have started the debugger, it establishes the ODBC connection and displays the Enter Unassigned Parameters dialog box, as shown.

Unassigned Parameters Dialog box

Enter values for any unassigned parameters in the Value field, then click OK. The T-SQL debugger interface appears and displays the text of the stored procedure:

T-SQL Debugger Interface

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconTheTSQLDebugger.asp (2 of 4) [11/17/2002 11:04:42 PM]


Welcome to the MSDN Library

Debugging Options

With the SQL statement displayed, several debugging options are available on the toolbar buttons and on the Debug menu. These options include:

● 2Go

● Set and clear breakpoints

● Step

● Step into subexpression

● Step over subexpression

● Run to cursor

● Stop debugging

● Restart

Views and Options


In addition to the code window containing the SQL statement you are debugging, the T-SQL debugger interface presents separate output windows for local and global variables, and for the
output (result set) of the query. The View menu also allows you to open a separate Call Stack window and a Temp Table Dump window, so that you can examine these as the code executes.

The Options menu lets you customize the appearance of the T-SQL debugger by changing the fonts and colors used for display.

Exiting from the T-SQL Debugger

When you are finished with your debugging session, click Exit on the File menu to close the debugger. To execute a query again, click Restart on the Debug menu.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconTheTSQLDebugger.asp (3 of 4) [11/17/2002 11:04:42 PM]


Welcome to the MSDN Library
Troubleshooting

If you are having problems getting T-SQL debugging to work, you will need to check the event log on the server. SDI.DLL will log events in the application section of the event viewer. COM or
distributed COM errors will log events in the system section of the viewer.

● Make sure that the two computers can communicate with each other. The easiest mechanism to do this is by typing ping and the computer name of the client at a command prompt on the server if you are running TCP/IP. If this fails, fix the connectivity
problem between the machines.

● Make sure the file SDI.DLL resides in the same directory as SQLSERVR.EXE. This will be in the binn sub-directory under the main SQL Server directory. The default is c:\mssql\binn.

● Ensure that the RPC services are started on the server machine. You do this by starting the control panel, opening the services application and checking that the Remote Procedure Call ( RPC ) Service is running and set to start automatically, as well as the
Remote Procedure Call ( RPC ) Locator.

● Ensure that SQL Server is not set to log on as the SystemAccount. You do this by starting the control panel, opening the services application and double clicking on the MSSQLServer service. If the service is set to run as the SystemAccount, change this so
the server will log on to a specific account that is valid to the domain that you are in. If debugging still fails, make sure that the account SQL Server started as has sufficient rights to launch an automation server on the client machine.

● If you see COM error 80080005 in the event log, make sure that you did not start remote automation (autmgr32) from the command prompt. Autmgr32.exe should only be running in the winstation of the account that SQL Server logged in as. Any other
winstation will cause problems. If this is the case, close down autmgr32.exe via the task manager and let the sdi.dll and autprx32.dll load autmgr32 via COM.

● Make sure Remote Automation is successfully installed on the server and client machines, if both the client and server do not have Distributed COM (DCOM) installed and loaded.

● If your client system is running Windows NT 4.0 or later, run DCOMCNFG and make sure that everyone has launch and access permission for vbsdicli.exe.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconTheTSQLDebugger.asp (4 of 4) [11/17/2002 11:04:42 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

The UserConnection Designer

See Also

Up One Level The UserConnection designer uses Visual Basic's ActiveX designer architecture to provide design-time support for programmatic data access. It allows you to create connection and query
objects (based on the RDO rdoConnection and rdoQuery objects) at design time. These connections and queries are persisted as project-level objects. You can pre-set properties, define new
Inserting a New UserConnection Object properties and methods, and write code behind the objects to catch events.

Inserting a New Query Object


Note The Data Environment designer is an improved version of the UserConnection designer. The UserConnection Designer is for RDO programming only.

This provides a simplified method for responding to events raised from connections and queries as well as for calling stored procedures and client-defined queries at run-time.

Here are the basic steps to using the UserConnection designer:

1. Enable the designer and insert it into your project.

2. Use the UserConnection object's property page to establish connection information and specify settings for properties that can be set at design time.

3. Create new Query objects for the connection by selecting stored procedures from the target database or inserting SQL code for user-defined queries.

4. Configure each Query object by setting properties on its property page.

5. Write Visual Basic code that creates an instance of the new UserConnection class and calls any of its queries as methods.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconConnectionQueryDesigner.asp [11/17/2002 11:04:47 PM]


Inserting a New UserConnection Object

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic > The UserConnection Designer

Visual Basic Concepts

Inserting a New UserConnection Object

See Also

To insert a new connection object

1. Make sure the Remote Data Object 2.0 library is referenced in the References dialog box available from the Project menu.

2. Make sure the designer is enabled by checking Microsoft UserConnection on the Designers tab of the Components dialog box, available on the Projects menu.

3. Insert the UserConnection designer into the project by selecting Microsoft UserConnection from the Add ActiveX Designer item on the Project menu.

The Connection Designer Properties Window

When you insert the UserConnection designer, a new connection class is added to the current project and brings up a visual representation of the class, overlaid with its properties window, shown
below.

UserConnection Properties Connection tab

The UserConnection properties window has three tabs: Connection, Authentication, and Miscellaneous.

Connection Properties
The Connection properties are used to establish connections to the server during design time (for retrieving a list of available stored procedures) and is also persisted in the new UserConnection
object so that you don't have to specify connection information when the class is created at run time. This connection information is just the data source name (or, if you select Use DSN-less
Connection String, the driver and server name) along with any special connection tokens specified in the "Other ODBC Attributes" box.

The Use ODBC Datasource box displays all DSNs on the current computer. You can also define a new DSN by clicking on the New button.

Authentication Properties

http://msdn.microsoft.com/library/en-us/vbcon98/...nInsertingNewUserConnectionObject.asp?frame=true (1 of 4) [11/17/2002 11:04:50 PM]


Inserting a New UserConnection Object

The authentication tab contains information needed for connecting to the data source specified in the connection information tab. These properties of the connection may or may not be persisted
with the new connection object, depending on the setting of the check boxes at the bottom of the page. See "Persistence of Authentication" below for more details.

Authentication tab

The user name and password text boxes are self-explanatory. The password box displays asterisks as the password is entered.

The Prompt Behavior box allows you to choose the prompt behavior for the rdoConnection object.

Persistence of Authentication
Due to concerns about security and password protection, there are two levels of persistence available for the UserConnection object's authentication properties. By default both of these levels are
turned off, so that no caching or persistence of authentication properties occurs.

If Save Connection Information for new Run-Mode Class is checked, the user name and password properties are stored in the properties of the actual class and are persisted in the built executable
or DLL.

If Save Connection Information for Design Time is checked, the user name and password properties persist only during design-time, and are not written into the built .exe or .dll file.

Miscellaneous Properties
The last tab on the connection property page allows the developer to adjust the Timeout properties and cursor library for the new UserConnection class.

Miscellaneous Properties

http://msdn.microsoft.com/library/en-us/vbcon98/...nInsertingNewUserConnectionObject.asp?frame=true (2 of 4) [11/17/2002 11:04:50 PM]


Inserting a New UserConnection Object

The Logon Timeout and Query Timeout values can be set to any values allowed in RDO 2.0.

The Cursor Driver combo box contains options that map to the RDO constants for the "CursorDriver" property.

The UserConnection designer form

After entering the properties to establish an ODBC connection for your UserConnection object, click OK to close the properties window. The new object appears in the main UserConnection form.

The UserConnection Form

http://msdn.microsoft.com/library/en-us/vbcon98/...nInsertingNewUserConnectionObject.asp?frame=true (3 of 4) [11/17/2002 11:04:50 PM]


Inserting a New UserConnection Object

The toolbar buttons at the top of the form allow you to add single or multiple queries, delete queries, examine or change query properties, and change global options for the UserConnection
designer.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/...nInsertingNewUserConnectionObject.asp?frame=true (4 of 4) [11/17/2002 11:04:50 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic > The UserConnection Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Inserting a New UserConnection Object

See Also

Up One Level To insert a new connection object

Inserting a New UserConnection Object


Inserting a New Query Object
1. Make sure the Remote Data Object 2.0 library is referenced in the References dialog box available from the Project menu.

2. Make sure the designer is enabled by checking Microsoft UserConnection on the Designers tab of the Components dialog box, available on the Projects menu.

3. Insert the UserConnection designer into the project by selecting Microsoft UserConnection from the Add ActiveX Designer item on the Project menu.

The Connection Designer Properties Window

When you insert the UserConnection designer, a new connection class is added to the current project and brings up a visual representation of the class, overlaid with its properties window,
shown below.

UserConnection Properties Connection tab

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconInsertingNewUserConnectionObject.asp (1 of 5) [11/17/2002 11:04:53 PM]


Welcome to the MSDN Library

The UserConnection properties window has three tabs: Connection, Authentication, and Miscellaneous.

Connection Properties
The Connection properties are used to establish connections to the server during design time (for retrieving a list of available stored procedures) and is also persisted in the new
UserConnection object so that you don't have to specify connection information when the class is created at run time. This connection information is just the data source name (or, if you select
Use DSN-less Connection String, the driver and server name) along with any special connection tokens specified in the "Other ODBC Attributes" box.

The Use ODBC Datasource box displays all DSNs on the current computer. You can also define a new DSN by clicking on the New button.

Authentication Properties
The authentication tab contains information needed for connecting to the data source specified in the connection information tab. These properties of the connection may or may not be
persisted with the new connection object, depending on the setting of the check boxes at the bottom of the page. See "Persistence of Authentication" below for more details.

Authentication tab

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconInsertingNewUserConnectionObject.asp (2 of 5) [11/17/2002 11:04:53 PM]


Welcome to the MSDN Library

The user name and password text boxes are self-explanatory. The password box displays asterisks as the password is entered.

The Prompt Behavior box allows you to choose the prompt behavior for the rdoConnection object.

Persistence of Authentication
Due to concerns about security and password protection, there are two levels of persistence available for the UserConnection object's authentication properties. By default both of these levels
are turned off, so that no caching or persistence of authentication properties occurs.

If Save Connection Information for new Run-Mode Class is checked, the user name and password properties are stored in the properties of the actual class and are persisted in the built
executable or DLL.

If Save Connection Information for Design Time is checked, the user name and password properties persist only during design-time, and are not written into the built .exe or .dll file.

Miscellaneous Properties
The last tab on the connection property page allows the developer to adjust the Timeout properties and cursor library for the new UserConnection class.

Miscellaneous Properties

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconInsertingNewUserConnectionObject.asp (3 of 5) [11/17/2002 11:04:53 PM]


Welcome to the MSDN Library

The Logon Timeout and Query Timeout values can be set to any values allowed in RDO 2.0.

The Cursor Driver combo box contains options that map to the RDO constants for the "CursorDriver" property.

The UserConnection designer form

After entering the properties to establish an ODBC connection for your UserConnection object, click OK to close the properties window. The new object appears in the main UserConnection
form.

The UserConnection Form

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconInsertingNewUserConnectionObject.asp (4 of 5) [11/17/2002 11:04:53 PM]


Welcome to the MSDN Library

The toolbar buttons at the top of the form allow you to add single or multiple queries, delete queries, examine or change query properties, and change global options for the UserConnection
designer.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconInsertingNewUserConnectionObject.asp (5 of 5) [11/17/2002 11:04:53 PM]


Inserting a New Query Object

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic > The UserConnection Designer

Visual Basic Concepts

Inserting a New Query Object

See Also

Once a new UserConnection object has been inserted into the project, you can add new Query objects to it. These query objects can be either stored procedure calls or user-defined SQL
statements. Each query object defined at design-time will automatically be available as a method of the new UserConnection class.

To add a Query object, click the leftmost button on the toolbar. The new Query object is added hierarchically below the UserConnection object, and its Properties Window appears.

Selecting Stored Procedures

Select Insert Stored Procedure to view the available stored procedures on the database. The UserConnection designer attempts to establish a connection to the database, using the connection
properties you entered. If successful, it enumerates the available stored procedures on the database, allowing you to select one to define the Query object:

Query Properties dialog box

Inserting User-Defined Queries

Choose Based on User-Defined SQL to create a local query against the remote database. This enables the SQL property box, into which you enter SQL statements to define your query.

Alternatively, you can click the Build button, which opens the MS-Query query design tool. MS-Query provides a visual interface that allows you to drag and drop database tables and fields, define
conditions and set relationships to define the query. When you exit from MS-Query, your visually-designed query is automatically translated into SQL code and inserted into the User-Defined SQL
property box.

For More Information For more information about using the MS-Query query builder, see MSQry32.hlp which is installed in the \Program Files\Common Files\Microsoft Shared\vba directory.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconInsertingNewQueryObject.asp?frame=true (1 of 3) [11/17/2002 11:04:58 PM]


Inserting a New Query Object

Setting Other Query Properties

In addition to the defining properties discussed above, the Query Property Page has two additional tabs for defining Parameters and advanced properties.

The Parameters tab on the query property page allows the developer to adjust properties for each parameter in the current query.

Parameters properties

The parameters shown in the Parameters list box are determined automatically from the query source, and cannot be changed here. Parameters are generated for each parameter marker in the
SQL statement for the query (or call statement for stored procedures). Parameter markers are designated by a "?" in accordance with the ODBC specification. For example, the following query
would contain two parameters:

SELECT * FROM authors WHERE state = ? AND zip = ?

The parameter properties that can be changed here are the Name, Direction, ODBC Binding Data Type, and Visual Basic Data Type.

The Name property can be changed to allow your Visual Basic code to recognize the parameter by a familiar sounding name, if its actual name is complex or not intuitive.

Setting the Direction of a parameter may be necessary for some ODBC databases for which the driver is not capable of determining the direction (input, input/output, or return values). The same
is true for the data types, and you may wish to override the default type conversion into Visual Basic data types for use with your code.

Advanced Query Properties


The Advanced tab of the Query Properties page allows for fine-tuning the query by setting limits and thresholds.

Advanced properties

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconInsertingNewQueryObject.asp?frame=true (2 of 3) [11/17/2002 11:04:58 PM]


Inserting a New Query Object

The Call Syntax text box lets you change the call syntax that RDO will use to call the stored procedure. This can be edited to adjust the number of parameters and presence of the return value.
Editing the call syntax is an advanced operation and should only be done by developers who understand the ramifications.

Using the UserConnection Object in Your Code

You can insert the UserConnection object into your Visual Basic code just as you would with any class, by creating an object variable and instantiating it with a new instance of the UserConnection
class you have defined. For example:

Option Explicit
Private MyConnect As MyConnection
Set MyConnect = New MyConnection

You can write your own code "behind" the inserted UserConnection object to sink events raised from the connection or any of the queries defined under it. You can also implement your own
methods, or write Property Get and Property Let procedures to implement your own properties, which are added to the type library for the new object.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconInsertingNewQueryObject.asp?frame=true (3 of 3) [11/17/2002 11:04:58 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic > The UserConnection Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Inserting a New Query Object

See Also

Up One Level Once a new UserConnection object has been inserted into the project, you can add new Query objects to it. These query objects can be either stored procedure calls or user-defined SQL
statements. Each query object defined at design-time will automatically be available as a method of the new UserConnection class.
Inserting a New UserConnection Object
Inserting a New Query Object To add a Query object, click the leftmost button on the toolbar. The new Query object is added hierarchically below the UserConnection object, and its Properties Window appears.

Selecting Stored Procedures

Select Insert Stored Procedure to view the available stored procedures on the database. The UserConnection designer attempts to establish a connection to the database, using the connection
properties you entered. If successful, it enumerates the available stored procedures on the database, allowing you to select one to define the Query object:

Query Properties dialog box

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconInsertingNewQueryObject.asp (1 of 4) [11/17/2002 11:05:00 PM]


Welcome to the MSDN Library

Inserting User-Defined Queries

Choose Based on User-Defined SQL to create a local query against the remote database. This enables the SQL property box, into which you enter SQL statements to define your query.

Alternatively, you can click the Build button, which opens the MS-Query query design tool. MS-Query provides a visual interface that allows you to drag and drop database tables and fields,
define conditions and set relationships to define the query. When you exit from MS-Query, your visually-designed query is automatically translated into SQL code and inserted into the User-
Defined SQL property box.

For More Information For more information about using the MS-Query query builder, see MSQry32.hlp which is installed in the \Program Files\Common Files\Microsoft Shared\vba directory.

Setting Other Query Properties

In addition to the defining properties discussed above, the Query Property Page has two additional tabs for defining Parameters and advanced properties.

The Parameters tab on the query property page allows the developer to adjust properties for each parameter in the current query.

Parameters properties

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconInsertingNewQueryObject.asp (2 of 4) [11/17/2002 11:05:00 PM]


Welcome to the MSDN Library

The parameters shown in the Parameters list box are determined automatically from the query source, and cannot be changed here. Parameters are generated for each parameter marker in
the SQL statement for the query (or call statement for stored procedures). Parameter markers are designated by a "?" in accordance with the ODBC specification. For example, the following
query would contain two parameters:

SELECT * FROM authors WHERE state = ? AND zip = ?

The parameter properties that can be changed here are the Name, Direction, ODBC Binding Data Type, and Visual Basic Data Type.

The Name property can be changed to allow your Visual Basic code to recognize the parameter by a familiar sounding name, if its actual name is complex or not intuitive.

Setting the Direction of a parameter may be necessary for some ODBC databases for which the driver is not capable of determining the direction (input, input/output, or return values). The
same is true for the data types, and you may wish to override the default type conversion into Visual Basic data types for use with your code.

Advanced Query Properties


The Advanced tab of the Query Properties page allows for fine-tuning the query by setting limits and thresholds.

Advanced properties

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconInsertingNewQueryObject.asp (3 of 4) [11/17/2002 11:05:00 PM]


Welcome to the MSDN Library

The Call Syntax text box lets you change the call syntax that RDO will use to call the stored procedure. This can be edited to adjust the number of parameters and presence of the return value.
Editing the call syntax is an advanced operation and should only be done by developers who understand the ramifications.

Using the UserConnection Object in Your Code

You can insert the UserConnection object into your Visual Basic code just as you would with any class, by creating an object variable and instantiating it with a new instance of the
UserConnection class you have defined. For example:

Option Explicit
Private MyConnect As MyConnection
Set MyConnect = New MyConnection

You can write your own code "behind" the inserted UserConnection object to sink events raised from the connection or any of the queries defined under it. You can also implement your own
methods, or write Property Get and Property Let procedures to implement your own properties, which are added to the type library for the new object.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconInsertingNewQueryObject.asp (4 of 4) [11/17/2002 11:05:00 PM]


Wizards Related to Data Access

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

Visual Basic Concepts

Wizards Related to Data Access

See Also

Three Visual Basic wizards can assist you in your data access programming:

● Data Form Wizard

● Data Object Wizard

● MS FlexGrid Wizard

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconOtherDataAccessTools.asp?frame=true [11/17/2002 11:05:11 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic

MSDN Library GO
Advanced Search Visual Basic Concepts

Wizards Related to Data Access

See Also

Up One Level Three Visual Basic wizards can assist you in your data access programming:

The Data View Window and Visual Database Tools


Format Objects ● Data Form Wizard

Data Object Wizard


The SQL Editor

● MS FlexGrid Wizard

Stored Procedures in the SQL Editor


Triggers in the SQL Editor
The T-SQL Debugger
Contact Us | E-Mail this Page | MSDN Flash Newsletter
The UserConnection Designer
Wizards Related to Data Access © 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconOtherDataAccessTools.asp [11/17/2002 11:05:12 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Reference >

MSDN Library GO
Advanced Search Visual Basic: Data Form Wizard

Data Form Wizard

See Also

Up One Level The Data Form Wizard is designed to automatically generate Visual Basic forms that contain individual bound controls and procedures used to manage information derived from database tables
and queries. You can use the Data Form Wizard to create either single query forms to manage the data from a single table or simple query, or Master/Detail type forms used to manage more
ActiveX Control Interface Wizard complex one-to-many data relationships. If you are using a control, you can also create a grid or datasheet type form. The Data Form Wizard is used in conjunction with only the ADO Data
control.
ActiveX Document Migration Wizard
Application Wizard
Use the Data Form Wizard to:
Class Builder Utility
Data Form Wizard
Rapidly build forms with controls bound to a data source.
Data Object Wizard

● Create single record, grid, and Master/Detail forms.

Package and Deployment Wizard ● Rapidly create prototype data-based forms.

Property Page Wizard


Since you can create three types of forms, some steps of the Data Form Wizard are different for each type.
Resource Editor Add-In
Visual Data Manager (VisData) Add-In ● To create single table forms or forms with a grid (datasheet) layout, the Data Form Wizard follows these steps:

Wizard Manager
● Introduction

● Database Type

● Database

● Form

● Record Source

● Control Selection

● Finished!

Note The grid or datasheet form layout is not available when you choose a code as a binding type.

● To create Master/Detail forms, the Data Form Wizard follows these steps:
● Introduction

● Database Type

● Form

● Master Record Source

● Detail Record Source

● Record Source Relation

● Control Selection

● Finished!

In addition to the previous steps, data forms that contain ADO Data controls, also have a Connect Information step.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/datfrm98/html/vbwizdataformwizard.asp (1 of 2) [11/17/2002 11:05:20 PM]


Welcome to the MSDN Library
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/datfrm98/html/vbwizdataformwizard.asp (2 of 2) [11/17/2002 11:05:20 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Reference >

MSDN Library GO
Advanced Search Visual Basic: Data Object Wizard

Data Object Wizard

See Also

Up One Level Assists you in generating code to create custom data sources and User Controls to display and manipulate data through stored procedures.

ActiveX Control Interface Wizard


ActiveX Document Migration Wizard Note You must first create a Data Environment with commands to retrieve and manipulate data before you can use the Data Object Wizard. The Data Object Wizard uses commands within
the Data Environment to retrieve and update your data. The types of commands you create are:
Application Wizard
Class Builder Utility ● A required command, the Select Command

Data Form Wizard ● Optional commands such as the Insert, Update, or Delete commands.

Data Object Wizard Use this add-in when you want to:
Package and Deployment Wizard
Property Page Wizard ● Create updatable recordsets from stored procedures.

Resource Editor Add-In ● Create User controls to display and manipulate data.

Generate Visual Basic code that reflects relationships between data.


Visual Data Manager (VisData) Add-In

● Create user controls that display and allow you to interact with lookup relationships.

Wizard Manager ● Have meaningful text descriptions instead of cryptic lookup values.

● Have meaningful text for NULL values

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dowiz98/html/vbdlgdataobjectgenerator.asp [11/17/2002 11:05:25 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic >

MSDN Library GO
Advanced Search Visual Basic: FlexGrid Wizard

Data Form Wizard —Select Grid Type

See Also

Allows you to select the type of MSHFlexGrid form you want to create.

Options
Grid Type

Lists options for the type of your MSHFlexGrid form.

● Standard — A simple grid type that displays your records in a data sheet.

● Outline — A grid type that automatically merges and groups your data.

With the standard grid, the user can create a data sheet that allows columns to be rearranged, and allows the data to be sorted by any column.

With the outline grid, the user can create an outline view of data by grouping values in columns that are sorted from left to right. Users can rearrange the columns to change the sorting and
grouping.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/flxwz98/html/vbwizmsflexgridwizardselectgridtype.asp [11/17/2002 11:05:29 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)

MSDN Library GO
Advanced Search Visual Basic Concepts

About the Data Environment Designer

See Also

Up One Level The Data Environment designer provides an interactive, design time environment for creating programmatic run-time data access. At design time, you set property values for Connection and
Command objects, write code to respond to ActiveX® Data Object (ADO) events, execute commands, and create aggregates and hierarchies. You can also drag Data Environment objects onto
Designing a DataEnvironment Object forms or reports to create data-bound controls.

Connection Objects
Command Objects With the Data Environment designer, you can accomplish the following tasks:

Command Hierarchies
Field Mapping ● Add a Data Environment designer to a Visual Basic project.

Create Connection objects.


Manipulating Your Data Environment

● Create Command objects based on stored procedures, tables, views, synonyms, and SQL statements.

Attaching Code to ADO Events ● Create hierarchies of commands based on a grouping of Command objects, or by relating one or more Command objects together.

Write and run code for Connection and Recordset objects.


Using a Data Environment with Your Application

● Drag fields within a Command object from the Data Environment designer onto a Visual Basic form or the Data Report designer.

Data Environment Programming Guidelines


The Data Environment Extensibility Object Model Differences Between the UserConnection and Data Environment Designers

Scenarios For Using the Data Environment Designer The Data Environment designer provides a means to easily access data in your Visual Basic project. In previous releases, you used the ActiveX UserConnection designer to create Remote Data
Objects (RDO) at design time. Now, you can create ADO objects at design time using the Data Environment designer. In addition to supporting all of the functionality of the UserConnection
designer, the Data Environment designer supports:

● Multiple Connection objects that allow you to access multiple data sources within a single Data Environment.

● Connection and Command objects that you can organize by either connection or object.

● OLE DB data sources, as well as ODBC data sources.

● Drag-and-drop functionality that allows you to drag fields and tables from your Data Environment designer onto a form or the Data Report ActiveX designer. Data-bound controls are automatically created on the form. You can also specify the default control
type that is created.

● Execution of commands included in your Data Environment as programmatic run-time methods.

● Programmatic access to a Data Environment that is bound to controls on a form without a variable reference, such as moving to a new record.

● The ability to relate Command objects to create a relation hierarchy, or to group Command objects to create a grouped hierarchy.

● The ability to create aggregates that automatically calculate values within any Command hierarchy.

● The ability to manually bind data-aware controls to Field objects within a Command object.

● The Data Environment extensibility object model, which allows you to create add-ins. These add-ins can programmatically manipulate any DataEnvironment object within a Visual Basic project.

Functionality Comparison: UserConnection designer vs. Data Environment designer

UserConnection designer Data Environment designer


Functionality

Data Access exposed using… Remote Data Objects (RDO). ActiveX Data Objects (ADO).

Objects exposed include... only one RDO connection with multiple queries. multiple ADO Connection and Command objects within one DataEnvironment object.

Events exposed include... only events from the UserConnection object. all ADO events for the Connection and Command object.

Direct data binding... cannot be used as a direct data source. can be directly bound to controls on a form.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingDataEnvironmentDesigner.asp (1 of 2) [11/17/2002 11:05:48 PM]


Welcome to the MSDN Library
Programmatic access exposes… queries as methods from the UserConnection object with one ResultSet property. Command objects as methods from the DataEnvironment object, with one RecordSet
property per Command object.

Design environment provides… a basic view that only displays the list of queries in the UserConnection. two views of objects that list Connection and Command objects, as well as the Field
objects returned from each Command object.

Topics

● Designing a DataEnvironment Object

● Connection Objects

● Command Objects

● Field Mapping

● Manipulating Your Data Environment

● Attaching Code to ADO Events

● Using a Data Environment with Your Application

● Data Environment Programming Guidelines

● The Data Environment Extensibility Object Model

● Scenarios For Using the Data Environment Designer

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingDataEnvironmentDesigner.asp (2 of 2) [11/17/2002 11:05:48 PM]


Designing a DataEnvironment Object

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

Visual Basic Concepts

Designing a DataEnvironment Object

See Also

At design time, you can use the Data Environment designer to create a DataEnvironment object. The DataEnvironment object can include Connection and Command objects, hierarchies
(relationships between Command objects), groupings, and aggregates. Before designing your DataEnvironment object, you should determine what information you want to present, identify the
databases that contain the information, and determine your run-time objective (for example, creating a Data Report or Hierarchical FlexGrid control).

Before you can access the Data Environment designer, you must reference it in Visual Basic.

To reference the Data Environment designer

1. On the Project menu, click References.

2. From the References dialog box, select Data Environment 1.0, and then click OK.

To add a Data Environment designer object to a new Visual Basic project

1. From the New tab of the New Project dialog box, choose Standard EXE project, and then click Open.

2. From the Project menu, choose Add Data Environment.

The Data Environment designer is added to your Visual Basic project, the Data Environment designer window appears, and a Connection object is added to your Data Environment.

Once you have added a Data Environment designer to your project, you can create a Connection; see the procedure in Connection Objects. Once a Connection is created, you can add Commands
to it; see the procedure in Command Objects.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconDesigningDEObject.asp?frame=true [11/17/2002 11:05:51 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Designing a DataEnvironment Object

See Also

Up One Level At design time, you can use the Data Environment designer to create a DataEnvironment object. The DataEnvironment object can include Connection and Command objects, hierarchies
(relationships between Command objects), groupings, and aggregates. Before designing your DataEnvironment object, you should determine what information you want to present, identify the
Designing a DataEnvironment Object databases that contain the information, and determine your run-time objective (for example, creating a Data Report or Hierarchical FlexGrid control).

Connection Objects
Command Objects Before you can access the Data Environment designer, you must reference it in Visual Basic.

Command Hierarchies
Field Mapping To reference the Data Environment designer

Manipulating Your Data Environment


Attaching Code to ADO Events 1. On the Project menu, click References.

2. From the References dialog box, select Data Environment 1.0, and then click OK.
Using a Data Environment with Your Application
Data Environment Programming Guidelines To add a Data Environment designer object to a new Visual Basic project
The Data Environment Extensibility Object Model
Scenarios For Using the Data Environment Designer 1. From the New tab of the New Project dialog box, choose Standard EXE project, and then click Open.

2. From the Project menu, choose Add Data Environment.

The Data Environment designer is added to your Visual Basic project, the Data Environment designer window appears, and a Connection object is added to your Data Environment.

Once you have added a Data Environment designer to your project, you can create a Connection; see the procedure in Connection Objects. Once a Connection is created, you can add
Commands to it; see the procedure in Command Objects.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDesigningDEObject.asp [11/17/2002 11:05:53 PM]


Connection Objects

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

Visual Basic Concepts

Connection Objects

See Also

To access data using your Data Environment, you must create a Connection object. Therefore, every Data Environment should include at least one Connection object. A Connection object
represents a connection to a remote database that is used as a data source.

Upon adding a Data Environment to your Visual Basic project, the Data Environment designer automatically includes a new connection, called Connection1. At design time, the Data Environment
opens the connection and obtains metadata from the connection, including database object names, table structures, and procedure parameters.

Note If Show properties immediately after object creation is selected in the Options dialog box, the Data Link Properties dialog box will appear when you add a Data Environment to
your project. This option is not selected by default.

Creating a Connection Object

The Add Connection function is available at all times and is independent of the existence of other objects.

To create a database connection

● Click Add Connection on the Data Environment designer toolbar.

-or–

Right-click your Data Environment designer and select Add Connection from the shortcut menu.

Once you have added a Connection, the Data Environment is updated to show the new Connection object. The default name for this object is "Connection," followed by a number, such as Connection1.

Use the following procedure to specify Connection object properties.

To set the Connection Name and Data Source

1. In the Visual Basic Properties window, change the default Name to a more meaningful name for your data source database. For example, you may wish to change Connection1 to "Northwind" if the data source is the Northwind database.

2. Right-click the Connection object and choose Properties to access the Data Link Properties dialog box.

3. From the Data Link Properties dialog box, specify the connection information on the Provider and Connection tabs. This is typically a database that contains data or stored procedures. You may select only one source for each Connection object.

Note Regardless of the selected data source type, the Data Environment accesses all data via ADO and OLE DB interfaces.

4. Click OK to apply the properties and close the dialog box.

Setting Logon Information

Logon information only needs to be supplied if the database being accessed via the Connection object requires authentication information. You can specify a different set of logon information to be
used at design time and run time. For example, you might want to develop your application using a system administrator user identification and password, but supply a general guest user
identification when the application is run.

Note Any logon information specified on the Data Link Properties dialog box is overridden by logon information specified on the Visual Basic Properties window.

To specify logon information

1. On the Visual Basic Properties window, specify the user identification and password to be used at design time and run time, if necessary. You can also specify the prompt behavior.

2. Set DesignSaveAuthentication to True if you want the specified information to persist for design time. This information is not written into the built executable file or dynamic-link library (DLL). If this option is False, any information in DesignUserName and
DesignPassword is lost once you close and re-open the project.

3. Set RunSaveAuthentication to True if you want the specified authentication used at run time. The authentication information is stored in the properties of the class and persists in the built executable file or DLL. If this option is False, any information in
RunUserName and RunPassword is lost once you close and re-open the project.

Note Since the password is not encrypted, for maximum security you should not specify your password to persist for run time or design time.

Setting Miscellaneous Connection Information

The miscellaneous connection information consists of advanced options that change how the database is accessed.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconConnectionObjects.asp?frame=true (1 of 2) [11/17/2002 11:08:59 PM]


Connection Objects

To specify miscellaneous information

1. On the Visual Basic Properties window, specify the following:


● The CursorLocation to be used for the connection. For information on cursors, see Choosing and Managing Cursors.

● Additional parameters for the connection string in ConnectionSource. Any string placed here is appended to the ConnectionString property when connecting to the data source. For example, Database=pubs.
2. Right-click the Connection object and choose Properties to access the Data Link Properties dialog box.

3. On the Advanced and All tabs, you can:


● Specify the number of seconds for the connection and command timeouts.

● Indicate permissions and network settings.


4. Click OK to apply the properties and close the Data Link Properties dialog box.

Note A Connection object is not opened until information is needed from the connection, such as a list of tables. When a Connection object is selected in the Data Environment outline view, the status bar text can be used to determine if the connection is
currently established (open).

Dragging From a Data View to Your Data Environment

You can automatically create Connection objects by dragging a connection from the Data View window to your Data Environment designer. This is an easy and efficient way to create Connection
objects that already exist in your Data View.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconConnectionObjects.asp?frame=true (2 of 2) [11/17/2002 11:08:59 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Connection Objects

See Also

Up One Level To access data using your Data Environment, you must create a Connection object. Therefore, every Data Environment should include at least one Connection object. A Connection object
represents a connection to a remote database that is used as a data source.
Designing a DataEnvironment Object
Connection Objects Upon adding a Data Environment to your Visual Basic project, the Data Environment designer automatically includes a new connection, called Connection1. At design time, the Data
Command Objects Environment opens the connection and obtains metadata from the connection, including database object names, table structures, and procedure parameters.

Command Hierarchies
Note If Show properties immediately after object creation is selected in the Options dialog box, the Data Link Properties dialog box will appear when you add a Data Environment to
Field Mapping your project. This option is not selected by default.
Manipulating Your Data Environment
Attaching Code to ADO Events Creating a Connection Object

Using a Data Environment with Your Application


Data Environment Programming Guidelines The Add Connection function is available at all times and is independent of the existence of other objects.

The Data Environment Extensibility Object Model


Scenarios For Using the Data Environment Designer To create a database connection

● Click Add Connection on the Data Environment designer toolbar.

-or–

Right-click your Data Environment designer and select Add Connection from the shortcut menu.

Once you have added a Connection, the Data Environment is updated to show the new Connection object. The default name for this object is "Connection," followed by a number, such as Connection1.

Use the following procedure to specify Connection object properties.

To set the Connection Name and Data Source

1. In the Visual Basic Properties window, change the default Name to a more meaningful name for your data source database. For example, you may wish to change Connection1 to "Northwind" if the data source is the Northwind database.

2. Right-click the Connection object and choose Properties to access the Data Link Properties dialog box.

3. From the Data Link Properties dialog box, specify the connection information on the Provider and Connection tabs. This is typically a database that contains data or stored procedures. You may select only one source for each Connection object.

Note Regardless of the selected data source type, the Data Environment accesses all data via ADO and OLE DB interfaces.

4. Click OK to apply the properties and close the dialog box.

Setting Logon Information

Logon information only needs to be supplied if the database being accessed via the Connection object requires authentication information. You can specify a different set of logon information to
be used at design time and run time. For example, you might want to develop your application using a system administrator user identification and password, but supply a general guest user
identification when the application is run.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconConnectionObjects.asp (1 of 2) [11/17/2002 11:09:00 PM]


Welcome to the MSDN Library

Note Any logon information specified on the Data Link Properties dialog box is overridden by logon information specified on the Visual Basic Properties window.

To specify logon information

1. On the Visual Basic Properties window, specify the user identification and password to be used at design time and run time, if necessary. You can also specify the prompt behavior.

2. Set DesignSaveAuthentication to True if you want the specified information to persist for design time. This information is not written into the built executable file or dynamic-link library (DLL). If this option is False, any information in DesignUserName
and DesignPassword is lost once you close and re-open the project.

3. Set RunSaveAuthentication to True if you want the specified authentication used at run time. The authentication information is stored in the properties of the class and persists in the built executable file or DLL. If this option is False, any information in
RunUserName and RunPassword is lost once you close and re-open the project.

Note Since the password is not encrypted, for maximum security you should not specify your password to persist for run time or design time.

Setting Miscellaneous Connection Information

The miscellaneous connection information consists of advanced options that change how the database is accessed.

To specify miscellaneous information

1. On the Visual Basic Properties window, specify the following:


● The CursorLocation to be used for the connection. For information on cursors, see Choosing and Managing Cursors.

● Additional parameters for the connection string in ConnectionSource. Any string placed here is appended to the ConnectionString property when connecting to the data source. For example, Database=pubs.
2. Right-click the Connection object and choose Properties to access the Data Link Properties dialog box.

3. On the Advanced and All tabs, you can:


● Specify the number of seconds for the connection and command timeouts.

● Indicate permissions and network settings.


4. Click OK to apply the properties and close the Data Link Properties dialog box.

Note A Connection object is not opened until information is needed from the connection, such as a list of tables. When a Connection object is selected in the Data Environment outline view, the status bar text can be used to determine if the connection is
currently established (open).

Dragging From a Data View to Your Data Environment

You can automatically create Connection objects by dragging a connection from the Data View window to your Data Environment designer. This is an easy and efficient way to create
Connection objects that already exist in your Data View.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconConnectionObjects.asp (2 of 2) [11/17/2002 11:09:00 PM]


Command Objects

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

Visual Basic Concepts

Command Objects

See Also

Command objects define specific detailed information about what data is retrieved from a database connection. Command objects can be based on either a database object (such as a table, view,
stored procedure or synonym) or a Structured Query Language (SQL) query. You can also create relationships between Command objects to retrieve a set of related data in the form of a hierarchy
(see Command Hierarchies).

Note To be valid, a Command object must be associated with a Connection object.

If a Command object returns data, it is "recordset returning," and the results can be accessed using a Recordset object available from the DataEnvironment object. However, if a Command object
does not return data (for example, stored procedures or SQL text that performs an update), it is "non-recordset returning." The Data Environment Designer automatically identifies whether the
Command is recordset returning. You can override this setting by using the Recordset Returning check box on the Advanced tab of the Command Properties dialog box.

At run time, how you access the Command object depends on whether the Command object is recordset returning. If the Command object is recordset returning, you can access the Command
object as either a property or method from the DataEnvironment object. If it is non-recordset returning, your Command object is only accessible as a method. See Using a Data Environment with
Your Application for more information.

Creating a Command Object

The Add Command function is available at all times and is independent of the existence of other objects. However, a Command object that is not associated with a Connection object is invalid.

If a Connection object can be identified from the current focus during the add process, the ActiveConnection property of the Command object is set to that Connection object. If a Connection
object is not identified, the Command object is invalid until you associate it with a connection.

To add a Command object

● Click Add Command in the Data Environment designer toolbar.

-or–

Right-click a Connection object, or your Data Environment designer, and choose Add Command from the shortcut menu.

Once a Command object is added, the Data Environment's outline view shows the new Command object. The default name for this object is "Command," followed by a number, such as Command1.

Use the following procedure to specify Command object properties.

To specify Command object properties

1. Right-click the Connection object and choose Properties to access the Command Properties dialog box.

2. Click the General tab, and set the following:

Item Purpose

Command Name Change the default Command Name to a more meaningful name for your database object. For example, you may wish to change Command1 to "Customers" if the Command object is based on a table called "customers."

Connection If the Command object was created from a Connection object's shortcut menu, the Connection name is automatically set. However, you can change this connection.

Note To be valid, each Command object must be associated with a Connection object.

Database Object Select the type of database object from the drop-down list. This can be a stored procedure, synonym, table, or view.

Object Name Select an object name from the drop-down list. The listed objects are from the connection and match the selected Database Object type.

–or–

SQL Statement If this is selected as your data source, type an SQL query that is valid for your database in the SQL Statement box.

-or–

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCommandObjects.asp?frame=true (1 of 3) [11/17/2002 11:09:14 PM]


Command Objects
3. If the Command object is based on a parameterized query or a stored procedure, it may have a parameters collection. To set the parameter properties, click the Parameters tab in the Command Properties dialog box.

4. Use the Relation, Grouping, and Aggregates tabs to define relationships and shape the data included in the Recordset. For more information, see Command Hierarchies.

5. Click the Advanced tab in the Command Properties dialog box to set the properties that change how the data is retrieved or manipulated at run time. On this tab, set the advanced properties that provide your Data Environment control over the Command
object properties and its resulting Recordset object.

6. Click OK to apply the properties to the new Command object and close the dialog box.

If a recordset-returning Command object was successfully created, you can click the expand (+) bitmap from the Data Environment designer's outline view to see a list of fields. If no fields are shown, the cause could be an empty Recordset, an invalid Command
object, or an invalid connection. If you are sure you have a valid connection, right-click the DataEnvironment icon, and make sure the Show Fields menu command is checked.

Customizing the Parameter Objects of a Command Object

If a Command object is based on a parameterized query or a stored procedure with parameters, the Command object has a Parameters collection. You may want to customize the Parameter
objects contained in the collection by changing the data type or making the name more descriptive. For more information, see ADO Parameters.

Changing the Properties of Associated Parameter Objects


The following procedure describes how you can change the properties of Parameter objects that are associated with a Command object.

To change a Command object's associated Parameter object properties

1. Right-click the Command object that you wish to customize, and then select Properties from the shortcut menu.

2. From the Parameters tab, select a Parameter object from the Parameter list box, and then set the following properties:

Item Purpose

Name Provide a unique, meaningful name for the selected Parameter object.

Direction Specify whether this is an input or output parameter, or both, or if the parameter is the return value from the procedure.

DataType Specify the data type to which the Parameter object is converted.

Precision Specify the maximum size, in bytes.

Scale Specify the maximum number of digits to the right of the decimal point.

Size Specify the maximum size, in bytes.

Host Data Type Specify the data type used when this Parameter object is referenced by the host application. Changing this setting affects the data types used in building the type library information for the host.

Required Specify whether the parameter value is required when the Command object is executed.

Note If a required parameter is not set when the Command object is executed, the command will fail.

Value Specify the default value that is used at run time (unless a value is provided programmatically), and if necessary, at design time, if the Command object must be executed to obtain the field information.

3. Click OK to apply the parameter properties to the selected Command object and exit the dialog box.

For more information, see ADO Parameters.

Dragging From a Data View to Your Data Environment

You can automatically create Command objects by dragging from the Data View window to your Data Environment designer. This is an easy and efficient way to create Command objects from
tables, views, or stored procedures that are listed in your Data View. If the connection associated with the Command object being dropped doesn't already exist in the Data Environment, a
Connection object is automatically created.

Creating Multiple Command Objects from Stored Procedures

You can create multiple Command objects in your Data Environment designer from stored procedures using the Insert Stored Procedures dialog box.

To insert multiple stored procedures

1. Click Insert Stored Procedures in the Data Environment designer toolbar.

-or–

Right-click a DataEnvironment or Connection object and choose Insert Stored Procedures from the shortcut menu.

2. In the Insert Stored Procedures dialog box, move one or more stored procedures from the Available list to the Add list using the arrows.

Use > to move the stored procedures to the Add list one at a time, or use >> to move all stored procedures at once. Use < to remove the stored procedures from the Add list one at a time, or use << to remove all stored procedures at once.

3. Once the stored procedures are in the Add list, click Insert to add them to your Data Environment. A new Command object is created for each stored procedure.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCommandObjects.asp?frame=true (2 of 3) [11/17/2002 11:09:14 PM]


Command Objects

Note The name of the Command object defaults to the name of the stored procedure.

4. Click Close to exit the dialog box.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCommandObjects.asp?frame=true (3 of 3) [11/17/2002 11:09:14 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Command Objects

See Also

Up One Level Command objects define specific detailed information about what data is retrieved from a database connection. Command objects can be based on either a database object (such as a table,
view, stored procedure or synonym) or a Structured Query Language (SQL) query. You can also create relationships between Command objects to retrieve a set of related data in the form of a
Designing a DataEnvironment Object hierarchy (see Command Hierarchies).

Connection Objects
Command Objects Note To be valid, a Command object must be associated with a Connection object.

Command Hierarchies
Field Mapping If a Command object returns data, it is "recordset returning," and the results can be accessed using a Recordset object available from the DataEnvironment object. However, if a Command
object does not return data (for example, stored procedures or SQL text that performs an update), it is "non-recordset returning." The Data Environment Designer automatically identifies
Manipulating Your Data Environment whether the Command is recordset returning. You can override this setting by using the Recordset Returning check box on the Advanced tab of the Command Properties dialog box.

Attaching Code to ADO Events


Using a Data Environment with Your Application At run time, how you access the Command object depends on whether the Command object is recordset returning. If the Command object is recordset returning, you can access the Command
object as either a property or method from the DataEnvironment object. If it is non-recordset returning, your Command object is only accessible as a method. See Using a Data Environment
Data Environment Programming Guidelines with Your Application for more information.

The Data Environment Extensibility Object Model


Scenarios For Using the Data Environment Designer Creating a Command Object

The Add Command function is available at all times and is independent of the existence of other objects. However, a Command object that is not associated with a Connection object is invalid.

If a Connection object can be identified from the current focus during the add process, the ActiveConnection property of the Command object is set to that Connection object. If a Connection
object is not identified, the Command object is invalid until you associate it with a connection.

To add a Command object

● Click Add Command in the Data Environment designer toolbar.

-or–

Right-click a Connection object, or your Data Environment designer, and choose Add Command from the shortcut menu.

Once a Command object is added, the Data Environment's outline view shows the new Command object. The default name for this object is "Command," followed by a number, such as Command1.

Use the following procedure to specify Command object properties.

To specify Command object properties

1. Right-click the Connection object and choose Properties to access the Command Properties dialog box.

2. Click the General tab, and set the following:

Item Purpose

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCommandObjects.asp (1 of 3) [11/17/2002 11:09:17 PM]


Welcome to the MSDN Library
Command Name Change the default Command Name to a more meaningful name for your database object. For example, you may wish to change Command1 to "Customers" if the Command object is based on a table called "customers."

Connection If the Command object was created from a Connection object's shortcut menu, the Connection name is automatically set. However, you can change this connection.

Note To be valid, each Command object must be associated with a Connection object.

Database Object Select the type of database object from the drop-down list. This can be a stored procedure, synonym, table, or view.

Object Name Select an object name from the drop-down list. The listed objects are from the connection and match the selected Database Object type.

–or–

SQL Statement If this is selected as your data source, type an SQL query that is valid for your database in the SQL Statement box.

-or–

3. If the Command object is based on a parameterized query or a stored procedure, it may have a parameters collection. To set the parameter properties, click the Parameters tab in the Command Properties dialog box.

4. Use the Relation, Grouping, and Aggregates tabs to define relationships and shape the data included in the Recordset. For more information, see Command Hierarchies.

5. Click the Advanced tab in the Command Properties dialog box to set the properties that change how the data is retrieved or manipulated at run time. On this tab, set the advanced properties that provide your Data Environment control over the Command
object properties and its resulting Recordset object.

6. Click OK to apply the properties to the new Command object and close the dialog box.

If a recordset-returning Command object was successfully created, you can click the expand (+) bitmap from the Data Environment designer's outline view to see a list of fields. If no fields are shown, the cause could be an empty Recordset, an invalid
Command object, or an invalid connection. If you are sure you have a valid connection, right-click the DataEnvironment icon, and make sure the Show Fields menu command is checked.

Customizing the Parameter Objects of a Command Object

If a Command object is based on a parameterized query or a stored procedure with parameters, the Command object has a Parameters collection. You may want to customize the Parameter
objects contained in the collection by changing the data type or making the name more descriptive. For more information, see ADO Parameters.

Changing the Properties of Associated Parameter Objects


The following procedure describes how you can change the properties of Parameter objects that are associated with a Command object.

To change a Command object's associated Parameter object properties

1. Right-click the Command object that you wish to customize, and then select Properties from the shortcut menu.

2. From the Parameters tab, select a Parameter object from the Parameter list box, and then set the following properties:

Item Purpose

Name Provide a unique, meaningful name for the selected Parameter object.

Direction Specify whether this is an input or output parameter, or both, or if the parameter is the return value from the procedure.

DataType Specify the data type to which the Parameter object is converted.

Precision Specify the maximum size, in bytes.

Scale Specify the maximum number of digits to the right of the decimal point.

Size Specify the maximum size, in bytes.

Host Data Type Specify the data type used when this Parameter object is referenced by the host application. Changing this setting affects the data types used in building the type library information for the host.

Required Specify whether the parameter value is required when the Command object is executed.

Note If a required parameter is not set when the Command object is executed, the command will fail.

Value Specify the default value that is used at run time (unless a value is provided programmatically), and if necessary, at design time, if the Command object must be executed to obtain the field information.

3. Click OK to apply the parameter properties to the selected Command object and exit the dialog box.

For more information, see ADO Parameters.

Dragging From a Data View to Your Data Environment

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCommandObjects.asp (2 of 3) [11/17/2002 11:09:17 PM]


Welcome to the MSDN Library
You can automatically create Command objects by dragging from the Data View window to your Data Environment designer. This is an easy and efficient way to create Command objects from
tables, views, or stored procedures that are listed in your Data View. If the connection associated with the Command object being dropped doesn't already exist in the Data Environment, a
Connection object is automatically created.

Creating Multiple Command Objects from Stored Procedures

You can create multiple Command objects in your Data Environment designer from stored procedures using the Insert Stored Procedures dialog box.

To insert multiple stored procedures

1. Click Insert Stored Procedures in the Data Environment designer toolbar.

-or–

Right-click a DataEnvironment or Connection object and choose Insert Stored Procedures from the shortcut menu.

2. In the Insert Stored Procedures dialog box, move one or more stored procedures from the Available list to the Add list using the arrows.

Use > to move the stored procedures to the Add list one at a time, or use >> to move all stored procedures at once. Use < to remove the stored procedures from the Add list one at a time, or use << to remove all stored procedures at once.

3. Once the stored procedures are in the Add list, click Insert to add them to your Data Environment. A new Command object is created for each stored procedure.

Note The name of the Command object defaults to the name of the stored procedure.

4. Click Close to exit the dialog box.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCommandObjects.asp (3 of 3) [11/17/2002 11:09:17 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Command Hierarchies

See Also

Up One Level A Command hierarchy is a group of recordset-returning Command objects that define an ADO hierarchical Recordset. Once a Command hierarchy is established, the Data Environment
designer builds an ADO SHAPE Command, which is executed at run time and results in an ADO hierarchical Recordset. For more information, see Data Shaping.
Relation Hierarchies
Grouping Command Objects The Data Environment designer provides an easy-to-use interface to create ADO Recordset hierarchies. You can build relation hierarchies, grouping hierarchies, and aggregate calculations.
Aggregates Once a hierarchy is built, at run time, you can navigate through multiple Recordsets as a single unit or bind each Recordset object to controls on a form.

Accessing Hierarchy Information and the SHAPE Command


You can use the Microsoft Hierarchical FlexGrid control to display the data from all the recordsets in the hierarchy at one time in a banded format. You can also bind the hierarchical recordset
to a set of controls on a form, as described in Binding Data to Your Data Environment.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCommandHierarchies.asp [11/17/2002 11:09:22 PM]


Relation Hierarchies

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies

Visual Basic Concepts

Relation Hierarchies

See Also

You can use the Data Environment designer to relate two or more Command objects together based on command data. The concept is similar to joining two related tables using a SQL SELECT
statement. However, the run-time result is a set of hierarchical recordsets instead of a flat table. This type of hierarchy is called a relation hierarchy.

A relation hierarchy consists of a parent Command object and one or more child Command objects that are related through linking the parent's Field objects to the child's fields and/or parameters.
In a relation hierarchy, the child Command objects become fields in the parent Command object.

For example, you might want to create a relation hierarchy between a Customers and Orders table. By relating the Orders table to the Customers table based on the CustID field, the Orders
recordset becomes a field in the Customers recordset. Thus, the value of this field in each row becomes a reference to a recordset that contains all the Orders for that particular Customer. This is
illustrated by the following figure.

Note All Command objects used in the relation hierarchy must be associated with the same Connection object. You cannot relate Commands from two different databases.

For more information on relation hierarchies, see Data Shaping.

Creating a Relation Hierarchy from Two Existing Command Objects

Once there are two Command objects at the same level in the Data Environment outline view, you can create a relation hierarchy, as described in the following procedure.

Note The Command objects involved in a relation hierarchy should be recordset returning. If not, on the Advanced tab of the Command Properties dialog box, choose Recordset Returning, and
click OK to apply the changes to the Command object.

To create a relation hierarchy from two existing Command objects

1. Right-click the Command object that will be the child in the relation, and click Properties on the shortcut menu to open the Command Properties dialog box.

2. Select the Relation tab and then choose Relate to a Parent Command Object.

3. In the Parent Command box, select the parent Command object's name. All Command objects that are associated with the same connection are shown, except for any Command object that is a child of the current Command object.

4. Define the relation between the two Command objects as follows:

Item Description

Parent Fields Select a field from the parent Command object. When added, this shows on the left side of the relate expression.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconRelationHierarchies.asp?frame=true (1 of 2) [11/17/2002 11:09:25 PM]


Relation Hierarchies

Child Fields/Parameters Select a field or parameter from the child Command object. When added, this shows on the right side of the key expression.

Note You must link all required parameters to fields in the parent Command object. If the required parameters are not linked, the hierarchy cannot be successfully executed.

Add After you have selected from both the Parent Fields and the Child Fields/Parameters lists, click Add. The new relation pair shows in the Relation Definition relate expression (for example, CustomerID TO CustomerID). Repeat this process until you
have all relations defined, as necessary.

Note You should relate the two Command objects on fields that contain similar data. For example, if one Command object returns data from an Orders table and another returns data from a Customers table, you should use a field that exists in both tables,
such as orderID.

Remove To remove a relation pair, select the pair in the display area and click Remove.

5. Click OK to accept the relation definitions and close the dialog box.

Note While you can relate any two Command objects, the Data Environment designer does not check for valid input. Therefore, if you specify an invalid relationship, the data retrieved may not be what you expect.

Once a relation is in place, you can use the Microsoft Hierarchical FlexGrid control to display the data as a hierarchy.

Creating a Child Command Object from a Parent Command Object

An easy way to directly construct a relation hierarchy is to create a child Command object from the parent Command object. To create a child Command object directly, first create the parent
Command object, as described in Command Objects, and then perform the following procedure.

Note The Command objects involved in a relation hierarchy should be recordset returning. If not, on the Advanced tab of the Command Properties dialog box, choose Recordset Returning, and
click OK to apply the changes to the Command object.

To create a child Command object from a parent Command object

1. On the Data Environment toolbar, click Add Child Command.

-or–

Right-click the parent Command object and click Add Child Command on the shortcut menu to open the Command Properties dialog box.

Note The child Command and parent Command objects' connection are the same.

2. The default Command Name (shown on the General tab of the Command Properties dialog box) of the child Command is the name of the Field object that will be appended to the parent Command object. You can change this name to a more meaningful,
unique name. For example, you may wish to name the child "Orders" if it is based on a database object called "orders."

Note On the General tab of the Command Properties dialog box, Connection is disabled. This is because the child and parent Command objects must be associated with the same Connection object.

3. Select the Relation tab, and define the relation by specifying the fields or parameters in each Command object that contain common data.

4. Click OK to create the child Command object and close the dialog box. If successfully created, the child Command object appears below its parent in the Data Environment outline view.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconRelationHierarchies.asp?frame=true (2 of 2) [11/17/2002 11:09:25 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies

MSDN Library GO
Advanced Search Visual Basic Concepts

Relation Hierarchies

See Also

Up One Level You can use the Data Environment designer to relate two or more Command objects together based on command data. The concept is similar to joining two related tables using a SQL SELECT
statement. However, the run-time result is a set of hierarchical recordsets instead of a flat table. This type of hierarchy is called a relation hierarchy.
Relation Hierarchies
Grouping Command Objects A relation hierarchy consists of a parent Command object and one or more child Command objects that are related through linking the parent's Field objects to the child's fields and/or
Aggregates parameters. In a relation hierarchy, the child Command objects become fields in the parent Command object.

Accessing Hierarchy Information and the SHAPE Command


For example, you might want to create a relation hierarchy between a Customers and Orders table. By relating the Orders table to the Customers table based on the CustID field, the Orders
recordset becomes a field in the Customers recordset. Thus, the value of this field in each row becomes a reference to a recordset that contains all the Orders for that particular Customer. This
is illustrated by the following figure.

Note All Command objects used in the relation hierarchy must be associated with the same Connection object. You cannot relate Commands from two different databases.

For more information on relation hierarchies, see Data Shaping.

Creating a Relation Hierarchy from Two Existing Command Objects

Once there are two Command objects at the same level in the Data Environment outline view, you can create a relation hierarchy, as described in the following procedure.

Note The Command objects involved in a relation hierarchy should be recordset returning. If not, on the Advanced tab of the Command Properties dialog box, choose Recordset Returning,
and click OK to apply the changes to the Command object.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRelationHierarchies.asp (1 of 2) [11/17/2002 11:09:27 PM]


Welcome to the MSDN Library

To create a relation hierarchy from two existing Command objects

1. Right-click the Command object that will be the child in the relation, and click Properties on the shortcut menu to open the Command Properties dialog box.

2. Select the Relation tab and then choose Relate to a Parent Command Object.

3. In the Parent Command box, select the parent Command object's name. All Command objects that are associated with the same connection are shown, except for any Command object that is a child of the current Command object.

4. Define the relation between the two Command objects as follows:

Item Description

Parent Fields Select a field from the parent Command object. When added, this shows on the left side of the relate expression.

Child Fields/Parameters Select a field or parameter from the child Command object. When added, this shows on the right side of the key expression.

Note You must link all required parameters to fields in the parent Command object. If the required parameters are not linked, the hierarchy cannot be successfully executed.

Add After you have selected from both the Parent Fields and the Child Fields/Parameters lists, click Add. The new relation pair shows in the Relation Definition relate expression (for example, CustomerID TO CustomerID). Repeat this process until
you have all relations defined, as necessary.

Note You should relate the two Command objects on fields that contain similar data. For example, if one Command object returns data from an Orders table and another returns data from a Customers table, you should use a field that exists in both
tables, such as orderID.

Remove To remove a relation pair, select the pair in the display area and click Remove.

5. Click OK to accept the relation definitions and close the dialog box.

Note While you can relate any two Command objects, the Data Environment designer does not check for valid input. Therefore, if you specify an invalid relationship, the data retrieved may not be what you expect.

Once a relation is in place, you can use the Microsoft Hierarchical FlexGrid control to display the data as a hierarchy.

Creating a Child Command Object from a Parent Command Object

An easy way to directly construct a relation hierarchy is to create a child Command object from the parent Command object. To create a child Command object directly, first create the parent
Command object, as described in Command Objects, and then perform the following procedure.

Note The Command objects involved in a relation hierarchy should be recordset returning. If not, on the Advanced tab of the Command Properties dialog box, choose Recordset Returning,
and click OK to apply the changes to the Command object.

To create a child Command object from a parent Command object

1. On the Data Environment toolbar, click Add Child Command.

-or–

Right-click the parent Command object and click Add Child Command on the shortcut menu to open the Command Properties dialog box.

Note The child Command and parent Command objects' connection are the same.

2. The default Command Name (shown on the General tab of the Command Properties dialog box) of the child Command is the name of the Field object that will be appended to the parent Command object. You can change this name to a more
meaningful, unique name. For example, you may wish to name the child "Orders" if it is based on a database object called "orders."

Note On the General tab of the Command Properties dialog box, Connection is disabled. This is because the child and parent Command objects must be associated with the same Connection object.

3. Select the Relation tab, and define the relation by specifying the fields or parameters in each Command object that contain common data.

4. Click OK to create the child Command object and close the dialog box. If successfully created, the child Command object appears below its parent in the Data Environment outline view.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRelationHierarchies.asp (2 of 2) [11/17/2002 11:09:27 PM]


Grouping Command Objects

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies

Visual Basic Concepts

Grouping Command Objects

See Also

You can create a Command hierarchy by grouping a Command object. When a Command object is grouped, the grouped fields are added to a grouping Command object that becomes the parent
of the original Command object. In the resulting recordsets, the grouping Command object contains a row for each unique set of values of the grouped fields.

For example, if the Command object that you want to group is called Customers, you can specify to group by its "Country" Field object and name the grouping Command object "ByCountry." The
resulting group hierarchy consists of a Command object named ByCountry that contains two fields: Country and Customers. This is illustrated by the following figures.

Original Customers Table

Customers Table Grouped ByCountry

A grouped-based hierarchy displays in the Data Environment outline view as a single Command object with two folders of fields, one for the grouping Command and the other for the original, or
detail, Command object.

Note The name of all grouping Command objects must be unique among all other Command objects within the current Data Environment. For example, if you are creating a group based on a
Field object named country, a logical group name may be "ByCountry."

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconGroupingCommandObjects.asp?frame=true (1 of 2) [11/17/2002 11:09:31 PM]


Grouping Command Objects

To group a Command object

1. Right-click the Command object and click Properties on the shortcut menu to access the Command Properties dialog box.

2. Click the Grouping tab, and then select Group Command Object. This indicates that this Command object is part of a group and enables other fields on the tab.

3. Change the default Grouping Command Name for the grouped Command object to a more logical name, if preferred. For example, if you are grouping the Field objects in a Customers table by country, you might call the group "ByCountry."

Note The default name is CommandName_Grouping where CommandName is the name of the selected Command object.

4. Select the grouping fields from the list appearing in the Fields in Command box. Choose either one field at a time by selecting the field and click > or click >> to select all fields simultaneously.

-or–

Alternatively, to deselect fields, select the field to remove and click <, or click << to deselect all fields simultaneously.

Note If no fields are available, the arrow buttons are disabled. In addition, if you use the Properties dialog box of a child Command object to establish a group, the fields that define the parent-child relationship must be included as fields for the group. The Data
Environment designer prohibits these fields from being removed.

5. Click OK to save the grouping and close the dialog box.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconGroupingCommandObjects.asp?frame=true (2 of 2) [11/17/2002 11:09:31 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies

MSDN Library GO
Advanced Search Visual Basic Concepts

Grouping Command Objects

See Also

Up One Level You can create a Command hierarchy by grouping a Command object. When a Command object is grouped, the grouped fields are added to a grouping Command object that becomes the
parent of the original Command object. In the resulting recordsets, the grouping Command object contains a row for each unique set of values of the grouped fields.
Relation Hierarchies
Grouping Command Objects For example, if the Command object that you want to group is called Customers, you can specify to group by its "Country" Field object and name the grouping Command object "ByCountry."
Aggregates The resulting group hierarchy consists of a Command object named ByCountry that contains two fields: Country and Customers. This is illustrated by the following figures.

Accessing Hierarchy Information and the SHAPE Command


Original Customers Table

Customers Table Grouped ByCountry

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconGroupingCommandObjects.asp (1 of 2) [11/17/2002 11:09:34 PM]


Welcome to the MSDN Library

A grouped-based hierarchy displays in the Data Environment outline view as a single Command object with two folders of fields, one for the grouping Command and the other for the original,
or detail, Command object.

Note The name of all grouping Command objects must be unique among all other Command objects within the current Data Environment. For example, if you are creating a group based on
a Field object named country, a logical group name may be "ByCountry."

To group a Command object

1. Right-click the Command object and click Properties on the shortcut menu to access the Command Properties dialog box.

2. Click the Grouping tab, and then select Group Command Object. This indicates that this Command object is part of a group and enables other fields on the tab.

3. Change the default Grouping Command Name for the grouped Command object to a more logical name, if preferred. For example, if you are grouping the Field objects in a Customers table by country, you might call the group "ByCountry."

Note The default name is CommandName_Grouping where CommandName is the name of the selected Command object.

4. Select the grouping fields from the list appearing in the Fields in Command box. Choose either one field at a time by selecting the field and click > or click >> to select all fields simultaneously.

-or–

Alternatively, to deselect fields, select the field to remove and click <, or click << to deselect all fields simultaneously.

Note If no fields are available, the arrow buttons are disabled. In addition, if you use the Properties dialog box of a child Command object to establish a group, the fields that define the parent-child relationship must be included as fields for the group. The
Data Environment designer prohibits these fields from being removed.

5. Click OK to save the grouping and close the dialog box.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconGroupingCommandObjects.asp (2 of 2) [11/17/2002 11:09:34 PM]


Aggregates

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies

Visual Basic Concepts

Aggregates

See Also

An aggregate is a special type of Field object that you can use to have data automatically calculated based on a hierarchy of Command objects. You can define an aggregate on any relation or
grouped-based hierarchy. Each aggregate you define adds a new Field object to the current Command object. At run time, you can access the calculated data just like any other field.

In addition, you can create a Grand Total Aggregate, which can be used on any top-level Command object to calculate its values. When a Grand Total Aggregate is created, a new Command object
is created as the parent of the Command object on which the calculated values are based. Thus, the existing Command object becomes a child Command object and is referenced through a field in
the parent Command object.

For example, if an aggregate is based on the CustID field, you can obtain the total number of orders for each customer. This is illustrated by the following figure.

The aggregate can be based any of the operations in the following table.

Operation Description

Any Returns one of the values from the rows of the selected field.

Average Returns the average of the values of the selected field.

Count Returns the count of the number of records of the selected field.

Maximum Returns the highest value of the selected field.

Minimum Returns the smallest value of the selected field.

Standard Deviation Returns the standard deviation of the selected field.

Sum Returns the sum of all the values of the selected field.

To create an aggregate within a Command hierarchy

1. Right-click any Command object and select Properties from the shortcut menu. (To create an aggregate other than a Grand Total, the Command object must have a child or be grouped.) The Command Properties dialog box appears.

2. Click the Aggregates tab. The Aggregates frame lists all currently defined aggregates.

3. Click Add to add an aggregate to the Aggregates box.

Note To delete an aggregate from the Aggregates box, select the aggregate to delete, and then click Remove.

4. Specify the Aggregate Settings information, as follows:

Item Description

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAggregates.asp?frame=true (1 of 2) [11/17/2002 11:09:37 PM]


Aggregates

Name The name of the Field object that will be added to the Command object. At run time, this field will contain the calculated aggregate value.

You can change this to a more meaningful, unique name that describes the aggregate. For example, if you are creating an aggregate that provides the average number of items on each order, an appropriate name may be AverageOrderNumber.

Function Select the operation to associate with the aggregate: Any, Average, Count, Maximum, Minimum, Standard Deviation, or Sum, as described above.

Aggregate On Select a grouping, a child Command object, or Grand Total from the drop-down list. The selected item is what the aggregate is based upon.

Note Grand Total is only available on top-level Command objects. Choosing Grand Total implies that an additional Command object will be created to provide a grand total of your data.

Field Choose a Field object on which to base the aggregate. For example, if the aggregate is to provide the average number of orders, specify the field that contains the quantity of orders.

Name If you have selected Grand Total in the Aggregate On box, specify a name for the Grand Total Command. If Grand Total is not selected, this option is disabled. Once created, the Grand Total Name displays as the name of a new top-level Command object within the Data
Environment.

Note The Grand Total Name can be the same as the Aggregate Name.

5. Click OK to save the aggregate definition and close the dialog box. The aggregate appears as a Field object of the selected Command object in the Data Environment outline view.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAggregates.asp?frame=true (2 of 2) [11/17/2002 11:09:37 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies

MSDN Library GO
Advanced Search Visual Basic Concepts

Aggregates

See Also

Up One Level An aggregate is a special type of Field object that you can use to have data automatically calculated based on a hierarchy of Command objects. You can define an aggregate on any relation or
grouped-based hierarchy. Each aggregate you define adds a new Field object to the current Command object. At run time, you can access the calculated data just like any other field.
Relation Hierarchies
Grouping Command Objects
In addition, you can create a Grand Total Aggregate, which can be used on any top-level Command object to calculate its values. When a Grand Total Aggregate is created, a new Command
Aggregates object is created as the parent of the Command object on which the calculated values are based. Thus, the existing Command object becomes a child Command object and is referenced
through a field in the parent Command object.
Accessing Hierarchy Information and the SHAPE Command
For example, if an aggregate is based on the CustID field, you can obtain the total number of orders for each customer. This is illustrated by the following figure.

The aggregate can be based any of the operations in the following table.

Operation Description

Any Returns one of the values from the rows of the selected field.

Average Returns the average of the values of the selected field.

Count Returns the count of the number of records of the selected field.

Maximum Returns the highest value of the selected field.

Minimum Returns the smallest value of the selected field.

Standard Deviation Returns the standard deviation of the selected field.

Sum Returns the sum of all the values of the selected field.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAggregates.asp (1 of 2) [11/17/2002 11:09:39 PM]


Welcome to the MSDN Library
To create an aggregate within a Command hierarchy

1. Right-click any Command object and select Properties from the shortcut menu. (To create an aggregate other than a Grand Total, the Command object must have a child or be grouped.) The Command Properties dialog box appears.

2. Click the Aggregates tab. The Aggregates frame lists all currently defined aggregates.

3. Click Add to add an aggregate to the Aggregates box.

Note To delete an aggregate from the Aggregates box, select the aggregate to delete, and then click Remove.

4. Specify the Aggregate Settings information, as follows:

Item Description

Name The name of the Field object that will be added to the Command object. At run time, this field will contain the calculated aggregate value.

You can change this to a more meaningful, unique name that describes the aggregate. For example, if you are creating an aggregate that provides the average number of items on each order, an appropriate name may be AverageOrderNumber.

Function Select the operation to associate with the aggregate: Any, Average, Count, Maximum, Minimum, Standard Deviation, or Sum, as described above.

Aggregate On Select a grouping, a child Command object, or Grand Total from the drop-down list. The selected item is what the aggregate is based upon.

Note Grand Total is only available on top-level Command objects. Choosing Grand Total implies that an additional Command object will be created to provide a grand total of your data.

Field Choose a Field object on which to base the aggregate. For example, if the aggregate is to provide the average number of orders, specify the field that contains the quantity of orders.

Name If you have selected Grand Total in the Aggregate On box, specify a name for the Grand Total Command. If Grand Total is not selected, this option is disabled. Once created, the Grand Total Name displays as the name of a new top-level Command object within the
Data Environment.

Note The Grand Total Name can be the same as the Aggregate Name.

5. Click OK to save the aggregate definition and close the dialog box. The aggregate appears as a Field object of the selected Command object in the Data Environment outline view.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAggregates.asp (2 of 2) [11/17/2002 11:09:39 PM]


Accessing Hierarchy Information and the SHAPE Command

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies

Visual Basic Concepts

Accessing Hierarchy Information and the SHAPE Command

See Also

For run time, the Data Environment constructs an ADO SHAPE Command that is used by ADO to create an ADO hierarchical Recordset. You can display this underlying ADO hierarchical Recordset
and ADO SHAPE Syntax. The hierarchy information shows the structure of the ADO Recordsets that are created at run time. This information is important if you wish to understand how the run-
time hierarchy of recordsets are structured. You need to know this when programmatically accessing the ADO hierarchical Recordset. In addition, you can copy the SHAPE Command and paste it
into code when you are programmatically creating hierarchies using ADO directly.

For more information, see ADO SHAPE Commands.

To view the underlying hierarchy information and SHAPE Command of a hierarchical Command object

1. Right-click the parent Command object and click Hierarchy Info on the shortcut menu. The Hierarchy Information dialog box appears.

Note If Hierarchy Info is unavailable, the Command object is either not a parent Command object or it is not using the SHAPE Command.

2. Select View Shape Command to display the underlying SHAPE Command of the current Command object.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAccessHierInfoSHAPECmd.asp?frame=true [11/17/2002 11:09:43 PM]


Welcome to the MSDN Library
All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies

MSDN Library GO
Advanced Search Visual Basic Concepts

Accessing Hierarchy Information and the SHAPE Command

See Also

Up One Level For run time, the Data Environment constructs an ADO SHAPE Command that is used by ADO to create an ADO hierarchical Recordset. You can display this underlying ADO hierarchical
Recordset and ADO SHAPE Syntax. The hierarchy information shows the structure of the ADO Recordsets that are created at run time. This information is important if you wish to understand
Relation Hierarchies how the run-time hierarchy of recordsets are structured. You need to know this when programmatically accessing the ADO hierarchical Recordset. In addition, you can copy the SHAPE
Command and paste it into code when you are programmatically creating hierarchies using ADO directly.
Grouping Command Objects
Aggregates For more information, see ADO SHAPE Commands.
Accessing Hierarchy Information and the SHAPE Command
To view the underlying hierarchy information and SHAPE Command of a hierarchical Command object

1. Right-click the parent Command object and click Hierarchy Info on the shortcut menu. The Hierarchy Information dialog box appears.

Note If Hierarchy Info is unavailable, the Command object is either not a parent Command object or it is not using the SHAPE Command.

2. Select View Shape Command to display the underlying SHAPE Command of the current Command object.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAccessHierInfoSHAPECmd.asp [11/17/2002 11:11:10 PM]


Field Mapping

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

Visual Basic Concepts

Field Mapping

See Also

One of the features of the Data Environment is that it allows you to drag fields from the Data Environment onto a form or report. When you are designing a Data Environment, you can specify
what control is created when the field is dropped based on the data type of the field. For example, you can have a Spin Edit Control created for all integer types. You can also specify a specific
control on a per-field basis.

There are three levels of controls that you can specify. When a field is dropped onto a form, the Data Environment looks for a control in the order described in the following table. The first level
that has a control associated with it is used.

Control Level Description

Field Object Within a DataEnvironment object, a control can be directly associated with a Field object in a Command object. The control is specified as a property of the Field object and is only applicable to that specific field.

If no control is specified for the dropped Field object, the Data Environment moves to the next level: ADO Data Type.

ADO Data Type A control can be associated with a specific ADO data type. For example, a control can be associated with the ADO data type adTinyInt. Thus, whenever a field of this type is dropped on the form (and it does not
have a control associated with the Field object), the control associated with the ADO data type is created.

Note These settings will affect all DataEnvironment objects on your system.

If no control is associated with the specific ADO data type, the Data Environment moves to the next level: Field Type Categories.

Field Type Categories Since there are a large number of ADO data types that store similar data, a set of Field Type categories are defined. For example, all integer-related data types (such as adBigInt, adTinyInt, and so forth) are
combined into a Field Type category of Integer. If no control is associated with the specific ADO data type, the control associated with the Field Type that contains the ADO data type is used.

If there is no control associated with the Field Type category, the system defaults to an intrinsic TextBox control.

There are two special Field Type categories: Caption and Multiple. The control associated with Caption is the control used when a label object is created next to a new control. The control
associated with Multiple appears when you complete a right-drag of a Command object, and is typically used to specify a grid control.

The following procedures describe how to set field mapping information for your drag and drop controls.

To change the Caption control for a single Field object

1. Right-click a Field object and click Properties on the shortcut menu.

2. In the Field Mapping frame, set the Control and the Caption.

3. Click OK to set the field mapping properties for the current Field object and close the dialog box.

To change the Caption control for more than one Field object at a time

1. Select a Command object and click Options on the Data Environment designer toolbar.

-or-

Right-click your DataEnvironment object and click Options on the shortcut menu.

2. From the Field Mapping tab of the Options dialog box, select Show All Data Types.

3. Select each Field object from the Category/Field Type and Control list, and change its control in the Control box.

4. Click OK to set the Caption control properties and close the dialog box.

To specify an ADO Data Type or Category control

1. Select a Command object and click Options on the Data Environment designer toolbar.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconFieldMapping.asp?frame=true (1 of 2) [11/17/2002 11:11:37 PM]


Field Mapping
-or-

Right-click your DataEnvironment object and click Options on the shortcut menu.

2. On the Field Mapping tab of the Options dialog box, select Show all data types, and then specify the control:

Control Description

ADO Data Type Select a Data Type (for example, adBinary) from the Default Control Association list, and then associate it with a Control list item.

Category Select a Category (for example, Binary) from the Default Control Association list, and then associate it with a Control list item.

3. Click OK to set the control properties and close the dialog box.

To prevent the creation of labels for Field objects

1. Select a Command object and click Options on the Data Environment designer toolbar.

-or-

Right-click your DataEnvironment object and choose Options from the shortcut menu.

2. On the Field Mapping tab of the Options dialog box, deselect Drag and Drop Field Captions. The Field object captions (labels) will not be created on a drag and drop function.

3. Click OK to set the control properties and close the dialog box.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconFieldMapping.asp?frame=true (2 of 2) [11/17/2002 11:11:37 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Field Mapping

See Also

Up One Level One of the features of the Data Environment is that it allows you to drag fields from the Data Environment onto a form or report. When you are designing a Data Environment, you can specify
what control is created when the field is dropped based on the data type of the field. For example, you can have a Spin Edit Control created for all integer types. You can also specify a specific
Designing a DataEnvironment Object control on a per-field basis.

Connection Objects
Command Objects There are three levels of controls that you can specify. When a field is dropped onto a form, the Data Environment looks for a control in the order described in the following table. The first level
that has a control associated with it is used.
Command Hierarchies
Field Mapping
Manipulating Your Data Environment Control Level Description

Attaching Code to ADO Events Field Object Within a DataEnvironment object, a control can be directly associated with a Field object in a Command object. The control is specified as a property of the Field object and is only applicable to that specific
field.

Using a Data Environment with Your Application


Data Environment Programming Guidelines If no control is specified for the dropped Field object, the Data Environment moves to the next level: ADO Data Type.

The Data Environment Extensibility Object Model


Scenarios For Using the Data Environment Designer
ADO Data Type A control can be associated with a specific ADO data type. For example, a control can be associated with the ADO data type adTinyInt. Thus, whenever a field of this type is dropped on the form (and it does not
have a control associated with the Field object), the control associated with the ADO data type is created.

Note These settings will affect all DataEnvironment objects on your system.

If no control is associated with the specific ADO data type, the Data Environment moves to the next level: Field Type Categories.

Field Type Categories Since there are a large number of ADO data types that store similar data, a set of Field Type categories are defined. For example, all integer-related data types (such as adBigInt, adTinyInt, and so forth) are
combined into a Field Type category of Integer. If no control is associated with the specific ADO data type, the control associated with the Field Type that contains the ADO data type is used.

If there is no control associated with the Field Type category, the system defaults to an intrinsic TextBox control.

There are two special Field Type categories: Caption and Multiple. The control associated with Caption is the control used when a label object is created next to a new control. The control
associated with Multiple appears when you complete a right-drag of a Command object, and is typically used to specify a grid control.

The following procedures describe how to set field mapping information for your drag and drop controls.

To change the Caption control for a single Field object

1. Right-click a Field object and click Properties on the shortcut menu.

2. In the Field Mapping frame, set the Control and the Caption.

3. Click OK to set the field mapping properties for the current Field object and close the dialog box.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconFieldMapping.asp (1 of 2) [11/17/2002 11:11:40 PM]


Welcome to the MSDN Library

To change the Caption control for more than one Field object at a time

1. Select a Command object and click Options on the Data Environment designer toolbar.

-or-

Right-click your DataEnvironment object and click Options on the shortcut menu.

2. From the Field Mapping tab of the Options dialog box, select Show All Data Types.

3. Select each Field object from the Category/Field Type and Control list, and change its control in the Control box.

4. Click OK to set the Caption control properties and close the dialog box.

To specify an ADO Data Type or Category control

1. Select a Command object and click Options on the Data Environment designer toolbar.

-or-

Right-click your DataEnvironment object and click Options on the shortcut menu.

2. On the Field Mapping tab of the Options dialog box, select Show all data types, and then specify the control:

Control Description

ADO Data Type Select a Data Type (for example, adBinary) from the Default Control Association list, and then associate it with a Control list item.

Category Select a Category (for example, Binary) from the Default Control Association list, and then associate it with a Control list item.

3. Click OK to set the control properties and close the dialog box.

To prevent the creation of labels for Field objects

1. Select a Command object and click Options on the Data Environment designer toolbar.

-or-

Right-click your DataEnvironment object and choose Options from the shortcut menu.

2. On the Field Mapping tab of the Options dialog box, deselect Drag and Drop Field Captions. The Field object captions (labels) will not be created on a drag and drop function.

3. Click OK to set the control properties and close the dialog box.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconFieldMapping.asp (2 of 2) [11/17/2002 11:11:40 PM]


Manipulating Your Data Environment

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

Visual Basic Concepts

Manipulating Your Data Environment

See Also

This section contains information on viewing objects within your Data Environment designer, modifying and deleting objects, refreshing Command and Connection objects, and setting Data
Environment designer options.

Data Environment Designer Views

The Data Environment designer window has an outline view that shows the defined Connection and Command objects. This outline view can be arranged either by object type or by connection.
You can also set this outline view to either display or hide the field objects of each Command object.

View By Connection
By Connection displays the objects grouped by connection, with the Command objects listed under the Connection object to which they are linked. Thus, you can easily view the association of
Command objects with Connection objects. All defined Command hierarchies retain their structure.

To view By Connection

● Click the Arrange by Connections button in the Data Environment designer toolbar.

Outline View By Connection

View By Object
By Object groups objects of the same type together. This enables you to focus on objects of a specific type, regardless of their associated connection.

To view By Object

● Click the Arrange by Objects button in the Data Environment designer toolbar.

Outline View By Object

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconManipulatingYourDE.asp?frame=true (1 of 4) [11/17/2002 11:11:48 PM]


Manipulating Your Data Environment

Hiding Field Objects in Your Data Environment Designer

By default, the Field objects of each Command object display in the outline view of the Data Environment designer. You can expand or collapse the view of these Field objects by clicking the plus
(+) or minus (-) bitmap associated with the Command object. However, you can hide all Field objects completely from the outline view to clearly view relationships between Command objects.

To hide the Field objects for all Command objects

1. Right-click on the DataEnvironment object. The DataEnvironment object is the top-most object in your Data Environment outline view.

2. Clear the selection of Show Fields from the shortcut menu.

Modifying an Object in Your Data Environment Designer

You can modify any existing Command or Connection object by accessing either its Properties dialog box or the Visual Basic Properties window. Common modifications include changing a
Command object's connection source, adjusting a Connection object's logon information, and renaming an object.

Note While using the Visual Basic Properties window provides a direct means of changing individual property values, it can be more difficult if you are unfamiliar with the properties associated
with the object.

To modify an existing Command or Connection object using its Properties dialog box

1. Right-click the Command or Connection object to modify, and then select Properties from the shortcut menu to access its Properties dialog box.

-or-

Double-click your Command or Connection object to open its Properties dialog box.

2. To change any of the Command object's properties, from the Command Properties dialog box, click the appropriate tab: General, Parameters, Relation, Grouping, Aggregates, or Advanced, and then make the appropriate changes. For information on each
tab's settings, click the tab, and then press F1 to access online Help for the Command object's properties.

Note When the source of a Command object is changed, the Data Environment updates its associated field and parameter information.

3. To change any of the Connection object's properties, from the Data Link Properties dialog box, click the appropriate tab: Provider, Connection, Advanced, or All, and then make the appropriate changes. For information on each tab's settings, press F1 or
Help to access the online Help for the Connection object's properties.

4. Click OK to apply the properties to the object.

To modify an existing Command or Connection object using the Visual Basic Properties window

1. Select the Command or Connection object from the drop-down list in the Visual Basic Properties window.

2. Choose either the Alphabetic or the Categorized tab, and then change the property information in the right column as necessary.

Renaming an Object in Your Data Environment Designer

Upon creation, objects in your Data Environment designer are given default names, such as Command1, Connection1, or DataEnvironment1. However, you can change these to more meaningful,
unique names. For example, if you are creating a connection based on the Northwind database, a logical name may be "Northwind." Likewise, if you are creating a command based on the
customer's table, a logical name may be "Customers."

Note When a Connection object is renamed, any Command objects associated with it automatically update in the ActiveConnectionName property. In addition, when a Command object is
renamed, its link to the Connection object and other Command objects is maintained.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconManipulatingYourDE.asp?frame=true (2 of 4) [11/17/2002 11:11:48 PM]


Manipulating Your Data Environment

To rename an object in your Data Environment designer

● Right-click the object that you wish to rename and choose Properties from the shortcut menu. The Properties dialog box appears. Type a new name in the Name box and click OK to apply the changes and exit the dialog box.

-or-

Right-click the Command or Connection object you wish to rename and choose Rename from the shortcut menu. The outline view is now in edit mode. Type the new name, and then press ENTER to accept the change.

-or-

On the Visual Basic Properties window, select the entry to the right of (Name), and type the new name.

Deleting an Object from Your Data Environment

You can remove DataEnvironment, Connection, or Command objects from your Data Environment designer. When deleting an object, a warning message appears, unless Prompt before deleting
objects is cleared in the Options dialog box. In addition, if the object selected for deletion has dependent objects, a message appears, asking if you also want to delete the dependent objects. For
example, a Connection object has dependent objects if it is associated with a Command object, or a Command object has dependent objects if it is involved in a relation or grouping hierarchy.

Caution Once a Connection object is deleted, any Command objects associated with it become invalid, and the ActiveConnectionName property for all its associated Command objects is cleared.

To delete a Command or Connection object from your Data Environment designer

1. Select the object that you wish to remove and press DELETE.

-or-

Right-click the Command or Connection object that you wish to remove and choose Delete from the shortcut menu.

2. If Prompt before deleting objects is selected in the Options dialog box, warning messages display to alert you to any affects of the delete.

Refreshing an Object in Your Data Environment Designer

The Refresh function differs in function between Connection and Command objects.

Refreshing Connection Objects


When a refresh is performed on a Connection object, the connection is closed and the internal cache is cleared of the metadata associated with the Connection object. In addition, refreshing a
Connection forces the Data Environment to open the connection. After the refresh, the next time a list of tables or stored procedures is accessed, the list is rebuilt.

Note Refreshing a Connection object does not automatically refresh its associated Command objects.

Refreshing Command Objects


When a refresh is performed on a Command object, all metadata stored with the object, including the Field and Parameter objects, is rebuilt. If the Command object's definition of the table or
stored procedure has changed, the changes are reflected in the Command object after the refresh.

Caution Refreshing a Command object removes user-defined data, including parameter and field mapping information. Once removed, it cannot be retrieved.

To refresh a Connection or Command object

● Select the Command or Connection object to refresh, and then click Refresh in the Data Environment designer toolbar.

-or-

Right-click the Command or Connection object to refresh, and choose Refresh from the shortcut menu.

Connection and Command objects are also refreshed whenever their respective source properties are modified.

Note The status bar text indicates whether a Connection object is open (connected).

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconManipulatingYourDE.asp?frame=true (3 of 4) [11/17/2002 11:11:48 PM]


Manipulating Your Data Environment

Changing Warning and Confirmation Dialog Box Display

You can change the display of warning and confirmation dialog boxes using the Options dialog box.

To change warning and confirmation dialog box display

1. Click Options in the Data Environment designer toolbar.

-or-

Right-click a DataEnvironment object and choose Options from the shortcut menu.

2. From the General tab of the Options dialog box, set the following:

Item Description

Prompt before deleting object When selected, a confirmation dialog box displays when you delete an object.

Note It is recommended that this option remain selected, so that the system presents an alert when deletion of an object affects other objects within your Data Environment.

Disable Warnings When not selected, warning messages appear when appropriate.

Prompt before executing command When selected, the system prompts you before executing a Command object.

Occasionally it is not possible for the Data Environment to obtain field information about a Command object from the data provider using its normal processes. When the Data Environment is unsuccessful in obtaining metadata about the Recordset of a
particular Command object, it attempts to obtain this information from the data provider by executing the Command object. Thus, your permission is requested before the Data Environment executes the user-defined code.

Note This situation generally only occurs for Command objects based on stored procedures or SQL text.

3. Click OK to apply the options to your Data Environment designer and close the Options dialog box.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconManipulatingYourDE.asp?frame=true (4 of 4) [11/17/2002 11:11:48 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Manipulating Your Data Environment

See Also

Up One Level This section contains information on viewing objects within your Data Environment designer, modifying and deleting objects, refreshing Command and Connection objects, and setting Data
Environment designer options.
Designing a DataEnvironment Object
Connection Objects Data Environment Designer Views
Command Objects
Command Hierarchies The Data Environment designer window has an outline view that shows the defined Connection and Command objects. This outline view can be arranged either by object type or by connection.
You can also set this outline view to either display or hide the field objects of each Command object.
Field Mapping
Manipulating Your Data Environment
Attaching Code to ADO Events View By Connection
Using a Data Environment with Your Application
Data Environment Programming Guidelines By Connection displays the objects grouped by connection, with the Command objects listed under the Connection object to which they are linked. Thus, you can easily view the association of
Command objects with Connection objects. All defined Command hierarchies retain their structure.
The Data Environment Extensibility Object Model
Scenarios For Using the Data Environment Designer To view By Connection

● Click the Arrange by Connections button in the Data Environment designer toolbar.

Outline View By Connection

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconManipulatingYourDE.asp (1 of 5) [11/17/2002 11:11:50 PM]


Welcome to the MSDN Library

View By Object
By Object groups objects of the same type together. This enables you to focus on objects of a specific type, regardless of their associated connection.

To view By Object

● Click the Arrange by Objects button in the Data Environment designer toolbar.

Outline View By Object

Hiding Field Objects in Your Data Environment Designer

By default, the Field objects of each Command object display in the outline view of the Data Environment designer. You can expand or collapse the view of these Field objects by clicking the
plus (+) or minus (-) bitmap associated with the Command object. However, you can hide all Field objects completely from the outline view to clearly view relationships between Command
objects.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconManipulatingYourDE.asp (2 of 5) [11/17/2002 11:11:50 PM]


Welcome to the MSDN Library
To hide the Field objects for all Command objects

1. Right-click on the DataEnvironment object. The DataEnvironment object is the top-most object in your Data Environment outline view.

2. Clear the selection of Show Fields from the shortcut menu.

Modifying an Object in Your Data Environment Designer

You can modify any existing Command or Connection object by accessing either its Properties dialog box or the Visual Basic Properties window. Common modifications include changing a
Command object's connection source, adjusting a Connection object's logon information, and renaming an object.

Note While using the Visual Basic Properties window provides a direct means of changing individual property values, it can be more difficult if you are unfamiliar with the properties
associated with the object.

To modify an existing Command or Connection object using its Properties dialog box

1. Right-click the Command or Connection object to modify, and then select Properties from the shortcut menu to access its Properties dialog box.

-or-

Double-click your Command or Connection object to open its Properties dialog box.

2. To change any of the Command object's properties, from the Command Properties dialog box, click the appropriate tab: General, Parameters, Relation, Grouping, Aggregates, or Advanced, and then make the appropriate changes. For information
on each tab's settings, click the tab, and then press F1 to access online Help for the Command object's properties.

Note When the source of a Command object is changed, the Data Environment updates its associated field and parameter information.

3. To change any of the Connection object's properties, from the Data Link Properties dialog box, click the appropriate tab: Provider, Connection, Advanced, or All, and then make the appropriate changes. For information on each tab's settings, press F1
or Help to access the online Help for the Connection object's properties.

4. Click OK to apply the properties to the object.

To modify an existing Command or Connection object using the Visual Basic Properties window

1. Select the Command or Connection object from the drop-down list in the Visual Basic Properties window.

2. Choose either the Alphabetic or the Categorized tab, and then change the property information in the right column as necessary.

Renaming an Object in Your Data Environment Designer

Upon creation, objects in your Data Environment designer are given default names, such as Command1, Connection1, or DataEnvironment1. However, you can change these to more
meaningful, unique names. For example, if you are creating a connection based on the Northwind database, a logical name may be "Northwind." Likewise, if you are creating a command based
on the customer's table, a logical name may be "Customers."

Note When a Connection object is renamed, any Command objects associated with it automatically update in the ActiveConnectionName property. In addition, when a Command object is
renamed, its link to the Connection object and other Command objects is maintained.

To rename an object in your Data Environment designer

● Right-click the object that you wish to rename and choose Properties from the shortcut menu. The Properties dialog box appears. Type a new name in the Name box and click OK to apply the changes and exit the dialog box.

-or-

Right-click the Command or Connection object you wish to rename and choose Rename from the shortcut menu. The outline view is now in edit mode. Type the new name, and then press ENTER to accept the change.

-or-

On the Visual Basic Properties window, select the entry to the right of (Name), and type the new name.

Deleting an Object from Your Data Environment

You can remove DataEnvironment, Connection, or Command objects from your Data Environment designer. When deleting an object, a warning message appears, unless Prompt before
deleting objects is cleared in the Options dialog box. In addition, if the object selected for deletion has dependent objects, a message appears, asking if you also want to delete the dependent
objects. For example, a Connection object has dependent objects if it is associated with a Command object, or a Command object has dependent objects if it is involved in a relation or
grouping hierarchy.

Caution Once a Connection object is deleted, any Command objects associated with it become invalid, and the ActiveConnectionName property for all its associated Command objects is
cleared.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconManipulatingYourDE.asp (3 of 5) [11/17/2002 11:11:50 PM]


Welcome to the MSDN Library

To delete a Command or Connection object from your Data Environment designer

1. Select the object that you wish to remove and press DELETE.

-or-

Right-click the Command or Connection object that you wish to remove and choose Delete from the shortcut menu.

2. If Prompt before deleting objects is selected in the Options dialog box, warning messages display to alert you to any affects of the delete.

Refreshing an Object in Your Data Environment Designer

The Refresh function differs in function between Connection and Command objects.

Refreshing Connection Objects


When a refresh is performed on a Connection object, the connection is closed and the internal cache is cleared of the metadata associated with the Connection object. In addition, refreshing a
Connection forces the Data Environment to open the connection. After the refresh, the next time a list of tables or stored procedures is accessed, the list is rebuilt.

Note Refreshing a Connection object does not automatically refresh its associated Command objects.

Refreshing Command Objects


When a refresh is performed on a Command object, all metadata stored with the object, including the Field and Parameter objects, is rebuilt. If the Command object's definition of the table or
stored procedure has changed, the changes are reflected in the Command object after the refresh.

Caution Refreshing a Command object removes user-defined data, including parameter and field mapping information. Once removed, it cannot be retrieved.

To refresh a Connection or Command object

● Select the Command or Connection object to refresh, and then click Refresh in the Data Environment designer toolbar.

-or-

Right-click the Command or Connection object to refresh, and choose Refresh from the shortcut menu.

Connection and Command objects are also refreshed whenever their respective source properties are modified.

Note The status bar text indicates whether a Connection object is open (connected).

Changing Warning and Confirmation Dialog Box Display

You can change the display of warning and confirmation dialog boxes using the Options dialog box.

To change warning and confirmation dialog box display

1. Click Options in the Data Environment designer toolbar.

-or-

Right-click a DataEnvironment object and choose Options from the shortcut menu.

2. From the General tab of the Options dialog box, set the following:

Item Description

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconManipulatingYourDE.asp (4 of 5) [11/17/2002 11:11:50 PM]


Welcome to the MSDN Library
Prompt before deleting object When selected, a confirmation dialog box displays when you delete an object.

Note It is recommended that this option remain selected, so that the system presents an alert when deletion of an object affects other objects within your Data Environment.

Disable Warnings When not selected, warning messages appear when appropriate.

Prompt before executing command When selected, the system prompts you before executing a Command object.

Occasionally it is not possible for the Data Environment to obtain field information about a Command object from the data provider using its normal processes. When the Data Environment is unsuccessful in obtaining metadata about the Recordset of a
particular Command object, it attempts to obtain this information from the data provider by executing the Command object. Thus, your permission is requested before the Data Environment executes the user-defined code.

Note This situation generally only occurs for Command objects based on stored procedures or SQL text.

3. Click OK to apply the options to your Data Environment designer and close the Options dialog box.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconManipulatingYourDE.asp (5 of 5) [11/17/2002 11:11:50 PM]


Attaching Code to ADO Events

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

Visual Basic Concepts

Attaching Code to ADO Events

See Also

ADO exposes a set of events from its Connection and Recordset objects. These events are fired so you can attach code to be executed when something occurs on the object. For example, a
MoveComplete event is fired on the Recordset object whenever a record is navigated.

To add code to an ADO Connection or Recordset event

1. Click View Code in the Data Environment designer toolbar.

-or-

Right-click a Connection or Command object and click View Code on the shortcut menu.

2. Select an object in the left drop-down list and then select an event in the right drop-down list.

3. Add code in the Code window, as appropriate.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAttachingCodeToADOEvents.asp?frame=true [11/17/2002 11:12:03 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Attaching Code to ADO Events

See Also

Up One Level ADO exposes a set of events from its Connection and Recordset objects. These events are fired so you can attach code to be executed when something occurs on the object. For example, a
MoveComplete event is fired on the Recordset object whenever a record is navigated.
Designing a DataEnvironment Object
Connection Objects To add code to an ADO Connection or Recordset event
Command Objects
Command Hierarchies 1. Click View Code in the Data Environment designer toolbar.

Field Mapping
Manipulating Your Data Environment
-or-

Attaching Code to ADO Events


Right-click a Connection or Command object and click View Code on the shortcut menu.

Using a Data Environment with Your Application 2. Select an object in the left drop-down list and then select an event in the right drop-down list.

Data Environment Programming Guidelines 3. Add code in the Code window, as appropriate.

The Data Environment Extensibility Object Model


Scenarios For Using the Data Environment Designer
Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAttachingCodeToADOEvents.asp [11/17/2002 11:12:05 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Using a Data Environment with Your Application

See Also

Up One Level At run-time, the Data Environment creates ADO Command and Connection objects for each Command and Connection object defined in the Data Environment designer. If the Command
object is marked as Recordset Returning (on the Advanced tab of the Command Properties dialog box), then an ADO Recordset object is also created. The ADO Command object is added as a
Binding Data to Your Data Environment method from the Data Environment run-time object, and the ADO Connection and Recordset objects are added as properties.

Dragging Objects to Create Data-Bound Controls


Navigating Recordsets There are two ways to use a Data Environment in your application at run time:

Programmatically Accessing Objects in Your Data Environment Designer


● As a direct data source for data binding to controls on a form.

● To programmatically create an instance of the Data Environment and execute its Command objects.

In addition, the run-time Data Environment contains Commands, Connections, and Recordsets collections. These 1-based collections offer another means of programmatically accessing the
ADO objects, allowing you to enumerate the various objects.

Note The index for the first member of the collection starts at the number one in 1-based collections. ADO objects are 0-based, thus the Fields and Parameters collections are 0-based, and
thus, start at zero.

In the Data Environment, the names of ADO Recordset objects are prefaced with "rs" to distinguish them from their corresponding Command objects. For example, a Command object named
Customers creates a Recordset object named rsCustomers. By default, Recordset objects are closed. When the Recordset object's corresponding Command method executes, the Recordset
object opens. For example, executing the Customers method opens the Recordset object of "rsCustomers." In addition, you can open a Recordset object directly using the ADO Open method.
Using this method, you can manipulate a Recordset object before it is opened.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingDEWithYourApp.asp [11/17/2002 11:12:15 PM]


Binding Data to Your Data Environment

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Using a Data Environment with Your Application

Visual Basic Concepts

Binding Data to Your Data Environment

See Also

Data-bound controls are the data-aware controls through which you can display information from a database. You can bind these data-aware controls to Command objects that have been defined
in a DataEnvironment object. At run-time, Visual Basic automatically opens these Command objects and their associated connections.

At run time, up to three data-aware properties define what the controls are bound to. The following table describes the controls you should use to set the data-aware properties of a Data
Environment's Recordset object or Recordset field.

Property Description

DataSource Specifies the name of the DataEnvironment object to be used as the data source, such as DataEnvironment1.

DataMember Specifies the name of the Command object in the DataSource, such as Customers.

DataField Specifies the name of the Field object from the DataMember, such as Country.

To bind a Visual Basic control to a DataEnvironment object

1. Drop a control, such as a TextBox, onto your Visual Basic form.

2. On the Properties window, click the DataSource property and select the DataEnvironment object that you wish to bind to your control.

3. Click the DataMember property and select the Command object within the Data Environment that contains the field that you wish to bind to your control.

Note When binding to a Command object that contains parameters, make sure the parameters contain a valid value in their Value property.

4. Click the DataField property, if applicable, and select the field from the Command object that you wish to bind to your control.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconBindingDataToYourDE.asp?frame=true [11/17/2002 11:12:18 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Using a Data Environment with Your Application

MSDN Library GO
Advanced Search Visual Basic Concepts

Binding Data to Your Data Environment

See Also

Up One Level Data-bound controls are the data-aware controls through which you can display information from a database. You can bind these data-aware controls to Command objects that have been
defined in a DataEnvironment object. At run-time, Visual Basic automatically opens these Command objects and their associated connections.
Binding Data to Your Data Environment
Dragging Objects to Create Data-Bound Controls At run time, up to three data-aware properties define what the controls are bound to. The following table describes the controls you should use to set the data-aware properties of a Data
Navigating Recordsets Environment's Recordset object or Recordset field.

Programmatically Accessing Objects in Your Data Environment Designer


Property Description

DataSource Specifies the name of the DataEnvironment object to be used as the data source, such as DataEnvironment1.

DataMember Specifies the name of the Command object in the DataSource, such as Customers.

DataField Specifies the name of the Field object from the DataMember, such as Country.

To bind a Visual Basic control to a DataEnvironment object

1. Drop a control, such as a TextBox, onto your Visual Basic form.

2. On the Properties window, click the DataSource property and select the DataEnvironment object that you wish to bind to your control.

3. Click the DataMember property and select the Command object within the Data Environment that contains the field that you wish to bind to your control.

Note When binding to a Command object that contains parameters, make sure the parameters contain a valid value in their Value property.

4. Click the DataField property, if applicable, and select the field from the Command object that you wish to bind to your control.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconBindingDataToYourDE.asp [11/17/2002 11:12:20 PM]


Dragging Objects to Create Data-Bound Controls

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Using a Data Environment with Your Application

Visual Basic Concepts

Dragging Objects to Create Data-Bound Controls

See Also

The process of creating and binding a control can be simplified by dragging a Command or Field object from the Data Environment designer and dropping it onto a Visual Basic form or report.

When this is done, Visual Basic creates a control with the DataSource, DataMember, and, if appropriate, DataField properties automatically set. The control created is based on the field mapping
information specified in the DataEnvironment object. In addition, if specified, a label is automatically created.

Dragging Objects from Your Data Environment Designer to a Form

The section below explains how the Data Environment determines what control should be created.

To drag Field or Command objects onto a Data Report, see Creating a Simple Data Report.

To drag a Field or Command object onto a form

1. Select a Field or Command object from the Data Environment designer. To select all Field objects within a Command object, select the Command object.

2. Drag the selected Field or Command object from the Data Environment designer to the form.

Each item dragged to the form creates a data-bound control that is based on the control associated with its source object. The dragged object's property setting links to the source object in the Data Environment.

To create a grid from a Command object

1. Select a Command object and right-drag it onto a Visual Basic form.

2. Select an option from the menu: Data Grid, multiple-bound controls, or any control associated with the multiple setting.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconBoundCtrlsViaDragNDropInDE.asp?frame=true [11/17/2002 11:12:29 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Using a Data Environment with Your Application

MSDN Library GO
Advanced Search Visual Basic Concepts

Dragging Objects to Create Data-Bound Controls

See Also

Up One Level The process of creating and binding a control can be simplified by dragging a Command or Field object from the Data Environment designer and dropping it onto a Visual Basic form or report.

Binding Data to Your Data Environment


Dragging Objects to Create Data-Bound Controls When this is done, Visual Basic creates a control with the DataSource, DataMember, and, if appropriate, DataField properties automatically set. The control created is based on the field
mapping information specified in the DataEnvironment object. In addition, if specified, a label is automatically created.
Navigating Recordsets
Programmatically Accessing Objects in Your Data Environment Designer
Dragging Objects from Your Data Environment Designer to a Form

The section below explains how the Data Environment determines what control should be created.

To drag Field or Command objects onto a Data Report, see Creating a Simple Data Report.

To drag a Field or Command object onto a form

1. Select a Field or Command object from the Data Environment designer. To select all Field objects within a Command object, select the Command object.

2. Drag the selected Field or Command object from the Data Environment designer to the form.

Each item dragged to the form creates a data-bound control that is based on the control associated with its source object. The dragged object's property setting links to the source object in the Data Environment.

To create a grid from a Command object

1. Select a Command object and right-drag it onto a Visual Basic form.

2. Select an option from the menu: Data Grid, multiple-bound controls, or any control associated with the multiple setting.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconBoundCtrlsViaDragNDropInDE.asp [11/17/2002 11:12:31 PM]


Navigating Recordsets

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Using a Data Environment with Your Application

Visual Basic Concepts

Navigating Recordsets

See Also

Once you have bound controls on a Visual Basic form to a DataEnvironment object, you can add navigation buttons that allow the user to move through data at run time.

To add navigation buttons to your Visual Basic form

1. Drop two Command buttons on your form. You will use these to navigate through your Data Environment's Recordset object.

2. Right-click your Visual Basic form and select View Code from the shortcut menu.

3. For the Previous button, add the following code to the Click event.

DECustomers.rsCustomers.MovePrevious

4. For the Next button, add the following code to the Click event.

DECustomers.rsCustomers.MoveNext

5. Click Run on the Visual Basic toolbar to run your form, and click the Previous and Next buttons to navigate between records.

Note You can use any ADO method in this procedure, such as MoveFirst or MoveNext. To add update and delete capabilities to your form, use the Update and Delete methods.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconNavigatingRecordsets.asp?frame=true [11/17/2002 11:12:35 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Using a Data Environment with Your Application

MSDN Library GO
Advanced Search Visual Basic Concepts

Navigating Recordsets

See Also

Up One Level Once you have bound controls on a Visual Basic form to a DataEnvironment object, you can add navigation buttons that allow the user to move through data at run time.

Binding Data to Your Data Environment


Dragging Objects to Create Data-Bound Controls To add navigation buttons to your Visual Basic form

Navigating Recordsets
Programmatically Accessing Objects in Your Data Environment Designer 1. Drop two Command buttons on your form. You will use these to navigate through your Data Environment's Recordset object.

2. Right-click your Visual Basic form and select View Code from the shortcut menu.

3. For the Previous button, add the following code to the Click event.

DECustomers.rsCustomers.MovePrevious

4. For the Next button, add the following code to the Click event.

DECustomers.rsCustomers.MoveNext

5. Click Run on the Visual Basic toolbar to run your form, and click the Previous and Next buttons to navigate between records.

Note You can use any ADO method in this procedure, such as MoveFirst or MoveNext. To add update and delete capabilities to your form, use the Update and Delete methods.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconNavigatingRecordsets.asp [11/17/2002 11:12:37 PM]


Programmatically Accessing Objects in Your Data Environment Designer

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Using a Data Environment with Your Application

Visual Basic Concepts

Programmatically Accessing Objects in Your Data Environment Designer

See Also

Once Connection or Command objects are created, you can programmatically access and manipulate these ADO Command, Connection, and Recordset objects as though you had created them
directly through ADO. This makes it possible for you to programmatically bind data-aware controls to a Command object or to fields within a Command object at run time. You can also dynamically
set properties on ADO Connection or Recordset objects while they are closed, and set parameter values before data binding.

In addition, when you programmatically access data exposed by the Data Environment, you have greater control over execution options and can create multiple instances of a DataEnvironment
object.

When a Command object is executed using a method or data binding, the following occurs:

● ADO objects are created for the associated Connection and Command objects, and the resulting Recordset. Also, the design-time properties from the Data Environment's objects transfer to the ADO objects.

● The ADO Connection opens.

● The ADO Command opens.

You can also programmatically create instances of your Data Environment by declaring a variable within a procedure using the DIM statement. For example:

Dim DE as New MyDE

Programmatically Manipulating Objects within Your Data Environment Designer

Each Command object that you create is exposed programmatically as a method from the DataEnvironment object. Therefore, to execute the Command object, you can execute the method from
the Data Environment.

In addition to exposing a method for each Command object, a Recordset object is also exposed, depending on the Recordset Returning property setting. Since it is not possible to surface both a
method and a property of the same name, the Recordsets are exposed as the name of the Command preceded by "rs."

Upon creation, the Recordset object is closed. When you execute the method off the Data Environment, the Recordset opens. In addition, you can manipulate the Recordset before and after it is
opened. For example, once the Recordset is opened, you can navigate to the next record using the MoveNext method.

All ADO Recordset methods and properties are available from the Recordset that is associated with the DataEnvironment object.

To programmatically access your Data Environment from a Visual Basic form

1. Drop a Command button on your form. The code attached to this button is used to step through each record within the Command object in your DataEnvironment object.

2. In the Click event of the button, add the following line of code in the Code window.

Dim DE as New MyDE


MyDE.Customers

Note This example assumes that there are no parameters associated with the Command object.

3. The records are available from the Recordset associated with the Data Environment. This has the same name as the Command object, preceded by "rs". Add the following code to move to the first record in the Customers Command object.

DE.rsCustomers.MoveFirst

At this point, all methods associated with an ADO Recordset are available for DE.rsCustomers, such as the methods used to add, update, delete, and step through records. For example, the following code uses ADO methods to loop through all records in the
recordset.

Do While DE.rsCustomers.EOF = False


Debug.Print DE.rsCustomers.Fields(1).Value
DE.rsCustomers.MoveNext
Loop

Programmatically Executing Objects

The following are examples of executing Command objects using the method and Recordset objects associated with the DataEnvironment object. The examples use a Command object that is
based on a recordset-returning stored procedure with two input parameters.

Executing a Command Object with Multiple Parameters

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAccessingObjectsInYourDE.asp?frame=true (1 of 2) [11/17/2002 11:12:46 PM]


Programmatically Accessing Objects in Your Data Environment Designer

If the Command object has multiple parameters, and you want to pass selected parameters, you must manually set the value of the parameters using the Parameters collection. Then, you must
use the Open method from the Command object. For example, the Command object "InsertCustomer" contains the parameter's identification, first name, and nickname. To execute this method
and include all parameters, you can use the following method:

MyDE.InsertCustomer "34","Fred","Freddy"

However, to only include the identification and first name, you would use the following code:

MyDE.Commands("InsertCustomer").Parameters("ID").value = "34"
MyDE.Commands("InsertCustomer").Parameters("Name").value = "Fred
MyDE.Commands("InsertCustomer").Execute

Executing a Command Object with Parameters


The following example shows recordset-returning stored procedures with two Parameter objects.

Dim MyDE As DataEnvironment1


Dim nRecords As Integer
Dim nSum As Long

MyDE.SalesTotalByCityState "Seattle","WA"
MyDE.RSSalesByCityState.MoveFirst
For nRecords = 1 To MyDE.RSSalesByCityState.RecordCount
nSum = nSum + MyDE.RSSalesByCityState.Fields("Invoice_Amt")
MyDE.RSSalesByCityState.MoveNext
Next nRecords
Debug.Print nSum

Following is a more complicated example that shows a Command object that is based on a stored procedure that returns both a Recordset object and a return value. The example also contains an
input and an output Parameter object.

Dim MyDE As DataEnvironment1


Dim sOutStatus As String, nNumRecords As Long
nNumRecords = MyDE.OrdersByEmployee("SMITH", sOutStatus)
If sOutStatus = "Succeeded" Then
MyDE.OrdersByEmployee.MoveFirst
While Not MyDE.RSOrdersByEmployee.EOF
Debug.Print MyDE.RSOrdersByEmployee.Fields("OrderDate")
MyDE.RSOrdersByEmployee.MoveNext
End
End If

Executing a Non-Recordset Returning Command Object


The following example shows a non-recordset-returning stored procedure with a return value and Parameter object. A common scenario is to use stored procedures to insert, update and delete
records. These stored procedures do not return Recordset objects, but do use input and output Parameter objects.

Dim MyDE As New DataEnvironment1


Dim sOutStatus As String, nNumRecordsAffected As Long
nNumRecords = MyDE.DeleteEmployee("34", sOutStatus)
If sOutStatus = "Succeeded" Then
Debug.Print nNumRecords + " employee(s) were deleted."
Else
Debug.Print "Delete was not successful."
End If

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAccessingObjectsInYourDE.asp?frame=true (2 of 2) [11/17/2002 11:12:46 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Using a Data Environment with Your Application

MSDN Library GO
Advanced Search Visual Basic Concepts

Programmatically Accessing Objects in Your Data Environment Designer

See Also

Up One Level Once Connection or Command objects are created, you can programmatically access and manipulate these ADO Command, Connection, and Recordset objects as though you had created
them directly through ADO. This makes it possible for you to programmatically bind data-aware controls to a Command object or to fields within a Command object at run time. You can also
Binding Data to Your Data Environment dynamically set properties on ADO Connection or Recordset objects while they are closed, and set parameter values before data binding.

Dragging Objects to Create Data-Bound Controls


Navigating Recordsets In addition, when you programmatically access data exposed by the Data Environment, you have greater control over execution options and can create multiple instances of a
DataEnvironment object.
Programmatically Accessing Objects in Your Data Environment Designer
When a Command object is executed using a method or data binding, the following occurs:

● ADO objects are created for the associated Connection and Command objects, and the resulting Recordset. Also, the design-time properties from the Data Environment's objects transfer to the ADO objects.

● The ADO Connection opens.

● The ADO Command opens.

You can also programmatically create instances of your Data Environment by declaring a variable within a procedure using the DIM statement. For example:

Dim DE as New MyDE

Programmatically Manipulating Objects within Your Data Environment Designer

Each Command object that you create is exposed programmatically as a method from the DataEnvironment object. Therefore, to execute the Command object, you can execute the method
from the Data Environment.

In addition to exposing a method for each Command object, a Recordset object is also exposed, depending on the Recordset Returning property setting. Since it is not possible to surface both
a method and a property of the same name, the Recordsets are exposed as the name of the Command preceded by "rs."

Upon creation, the Recordset object is closed. When you execute the method off the Data Environment, the Recordset opens. In addition, you can manipulate the Recordset before and after it
is opened. For example, once the Recordset is opened, you can navigate to the next record using the MoveNext method.

All ADO Recordset methods and properties are available from the Recordset that is associated with the DataEnvironment object.

To programmatically access your Data Environment from a Visual Basic form

1. Drop a Command button on your form. The code attached to this button is used to step through each record within the Command object in your DataEnvironment object.

2. In the Click event of the button, add the following line of code in the Code window.

Dim DE as New MyDE


MyDE.Customers

Note This example assumes that there are no parameters associated with the Command object.

3. The records are available from the Recordset associated with the Data Environment. This has the same name as the Command object, preceded by "rs". Add the following code to move to the first record in the Customers Command object.

DE.rsCustomers.MoveFirst

At this point, all methods associated with an ADO Recordset are available for DE.rsCustomers, such as the methods used to add, update, delete, and step through records. For example, the following code uses ADO methods to loop through all records in the
recordset.

Do While DE.rsCustomers.EOF = False


Debug.Print DE.rsCustomers.Fields(1).Value

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAccessingObjectsInYourDE.asp (1 of 2) [11/17/2002 11:12:47 PM]


Welcome to the MSDN Library
DE.rsCustomers.MoveNext
Loop

Programmatically Executing Objects

The following are examples of executing Command objects using the method and Recordset objects associated with the DataEnvironment object. The examples use a Command object that is
based on a recordset-returning stored procedure with two input parameters.

Executing a Command Object with Multiple Parameters


If the Command object has multiple parameters, and you want to pass selected parameters, you must manually set the value of the parameters using the Parameters collection. Then, you
must use the Open method from the Command object. For example, the Command object "InsertCustomer" contains the parameter's identification, first name, and nickname. To execute this
method and include all parameters, you can use the following method:

MyDE.InsertCustomer "34","Fred","Freddy"

However, to only include the identification and first name, you would use the following code:

MyDE.Commands("InsertCustomer").Parameters("ID").value = "34"
MyDE.Commands("InsertCustomer").Parameters("Name").value = "Fred
MyDE.Commands("InsertCustomer").Execute

Executing a Command Object with Parameters


The following example shows recordset-returning stored procedures with two Parameter objects.

Dim MyDE As DataEnvironment1


Dim nRecords As Integer
Dim nSum As Long

MyDE.SalesTotalByCityState "Seattle","WA"
MyDE.RSSalesByCityState.MoveFirst
For nRecords = 1 To MyDE.RSSalesByCityState.RecordCount
nSum = nSum + MyDE.RSSalesByCityState.Fields("Invoice_Amt")
MyDE.RSSalesByCityState.MoveNext
Next nRecords
Debug.Print nSum

Following is a more complicated example that shows a Command object that is based on a stored procedure that returns both a Recordset object and a return value. The example also
contains an input and an output Parameter object.

Dim MyDE As DataEnvironment1


Dim sOutStatus As String, nNumRecords As Long
nNumRecords = MyDE.OrdersByEmployee("SMITH", sOutStatus)
If sOutStatus = "Succeeded" Then
MyDE.OrdersByEmployee.MoveFirst
While Not MyDE.RSOrdersByEmployee.EOF
Debug.Print MyDE.RSOrdersByEmployee.Fields("OrderDate")
MyDE.RSOrdersByEmployee.MoveNext
End
End If

Executing a Non-Recordset Returning Command Object


The following example shows a non-recordset-returning stored procedure with a return value and Parameter object. A common scenario is to use stored procedures to insert, update and
delete records. These stored procedures do not return Recordset objects, but do use input and output Parameter objects.

Dim MyDE As New DataEnvironment1


Dim sOutStatus As String, nNumRecordsAffected As Long
nNumRecords = MyDE.DeleteEmployee("34", sOutStatus)
If sOutStatus = "Succeeded" Then
Debug.Print nNumRecords + " employee(s) were deleted."
Else
Debug.Print "Delete was not successful."
End If

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAccessingObjectsInYourDE.asp (2 of 2) [11/17/2002 11:12:47 PM]


Data Environment Programming Guidelines

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

Visual Basic Concepts

Data Environment Programming Guidelines

See Also

The Data Environment designer allows the quick and easy building of hierarchical recordsets at design time. Programming the resulting DataEnvironment object, however, requires a knowledge of the ADO
programming model combined with characteristics of hierarchical recordsets. Below are the major points to visit when programming the DataEnvironment object.

Note The phrase "Data Environment designer" refers to the designer and its features. The phrase "DataEnvironment object" refers to the resulting programming object of the Data Environment designer.

Requerying the Recordset

Requerying a DataEnvironment-built recordset presents a few issues to be aware of. If you are using controls that are bound to the DataEnvironment, you must rebind those controls after requerying the
recordset. You can rebind the controls on a form to the DataEnvironment object by setting the DataMember, DataSource, and DataField properties wherever applicable.

Rebind After Using Requery Method


Whenever you query the database using the Requery method, you must rebind the controls to the appropriate recordset objects, as shown in the example below:

deNwind.rsCustomers.Requery
' Rebind a TextBox control named txtCustomer and a DataGrid
' control named grdData.
With txtCustomer
Set .DataSource = deNwind
.DataMember = "Customers"
.DataField = "CompanyName"
End With
With grdData
.DataMember = "customers"
Set .DataSource = deNwind
End With

Note The Data Environment designer automatically prepends references to Command objects with "rs"—thus Customers becomes rsCustomers. Also notice that the DataEnvironment object contains a
"Customers" method. By invoking the method, you can open its recordset.

Closing and Reopening the Recordset

When you close a recordset, the controls bound to that recordset no longer listen for events broadcasted by that recordset to notify them of changes. If you reopen the recordset, the data for that recordset will
not appear in the controls until you rebind them.

Creating a Parameterized Query


The example below demonstrates how to create a parameterized query with the Data Environment designer.

To create a parameterized query

1. Create a new project and add a Data Environment designer to the project.

2. On the Data Environment designer, create a Connection object and configure it to connect to the SQL Server Pubs database.

3. Right-click the Connection object and click Add Command.

4. Rename the Command object CommandQuery.

5. Right-click the Command object and click Properties.

6. On the General tab, click SQL Statement and type the following parameterized query:

SELECT * FROM Authors Where Au_ID = ?

7. Click the Parameters tab. (A message will appear informing you that not enough information has been supplied. Click OK.)

A new Input parameter will have been created for you. You can create further parameters, if needed, or set properties of the parameter. If you are using the Access OLE DB Provider or ODBC Driver, see the section below entitled "Paramaterized Queries and the Access OLE DB
Provider and ODBC Driver."

8. Click OK to close the dialog box.

9. On the default form, draw two TextBox controls and a CommandButton control.

10. Add the code below to the Form object's code window:

Option Explicit
Private Sub Command1_Click()
' You must close the recordset before changing the parameter.
If DataEnvironment1.rsCommandQuery.State = adStateOpen Then
DataEnvironment1.rsCommandQuery.Close
End If
' Reopen the recordset with the input parameter supplied by
' the TextBox control.
DataEnvironment1.CommandQuery Text1.Text
With Text2
.DataField = "AU_LName"

http://msdn.microsoft.com/library/en-us/vbcon98/...aEnvironmentProgrammingGuidelines.asp?frame=true (1 of 4) [11/17/2002 11:12:58 PM]


Data Environment Programming Guidelines
.DataMember = "CommandQuery"
Set .DataSource = DataEnvironment1
End With
End Sub

Private Sub Form_Load()


' Supply a default value.
Text1.Text = "172-32-1172"
' Change the CommandButton caption.
Command1.Caption = "Run Query"
End Sub

11. Run the project and click the button. Change the text in Text1 to run another query.

Parameterized Queries At Run Time

It's possible to build a parameterized query with the Data Environment designer and have controls bound to that DataMember. That query will run when the form is loaded. If you don't have the value of the
parameter set ahead of time, the query will fail. You'll have a closed recordset and you'll need to re-bind your controls before explicitly running the query. To avoid this, at design time be sure to supply a default
value for the parameter (on the Parameters tab). Alternatively, at run time, simply make sure you call the Command explicitly before displaying a control bound to that Command.

Paramaterized Queries and the Access OLE DB Provider and ODBC Driver

Due to limitations of the Microsoft® Access OLE DB provider and ODBC driver, parameterized queries are not fully supported in the Data Environment when connecting to an Access database, because the driver
and provider do not return information about parameters (like data type and direction) in the query.

Setting the Required Property for Stored Procedure Parameters


When running stored procedures from the DataEnvironment, how the Required property of a parameter is set depends on whether or not the stored procedure command is a child command in a hierarchy.

Stored Procedure as Child Commands: Optional Parameters Only

Although it's possible to insert a stored procedure into a hierarchy as a child command, there are two conditions that must be met:

● The stored procedure must not have any required parameters.

● After inserting the stored procedure into a hierarchy, you must set the Required check box for any parameters to False.

To create a stored procedure as a child command

1. Right-click an existing Command object and click Add Child Command.

2. Right-click the new Command object and click Properties.

3. By default, the Database Object is set to Stored Procedure. Click the Object Name box to see a list of stored procedures and select one.

4. Click the Parameters tab.

5. Select any parameter except RETURN_VALUE.

6. Set the Required property to False.

Setting Required Parameters for Inserted Stored Procedures with SQLServer Required

When using SQLServer and stored procedures, it's possible to create stored procedures that have optional parameters. However, if the stored procedure is not a child object in a hierarchy, optional parameters
are not accepted, and instead must be supplied by your code.

An example of a stored procedure with an optional parameter (@idCol) is shown below:

CREATE PROCEDURE OptionalParametersNotAllowed


(@IDCol smallint = NULL)
AS
IF @IDCol = NULL
select count(SupplierID) from Products
ELSE
select count(SupplierID) from Products where SupplierID= @IDCol

With the Data Environment designer, you can insert the stored procedure by right-clicking a Connection object and clicking Insert Stored Procedures. As shown above, you can set properties of the stored
procedure's parameters by right-clicking the resulting Command object, clicking Properties, then clicking the Parameters tab. While it's possible to set the Required option for the parameter to False, the
DataEnvironment object will generate an error message ("Argument not optional") unless a value is supplied. To work around this situation, be sure to supply a value as shown in the code below:

Private Sub Command1_Click()


' Open the connection.
DE.Connection1.Open , "sa"
' Run the stored procedure with a value.
DE.dbo_ OptionalParametersNotAllowed 8
Debug.Print DE.rsdbo_OptionalParametersNotAllowed.Fields(0).Value
' Free resources
DE.Connection1.Close
Set DE = Nothing
End Sub

Enabling the MTS SetAbort Method

If you use your DataEnvironment object in an MTS component with its default settings, the work done by the DataEnvironment is not in the MTS transaction. Thus the SetAbort method will not roll back the work
done by the DataEnvironment object. To ensure that the SetAbort method will roll back the DataEnvironment work, there are two methods:

http://msdn.microsoft.com/library/en-us/vbcon98/...aEnvironmentProgrammingGuidelines.asp?frame=true (2 of 4) [11/17/2002 11:12:58 PM]


Data Environment Programming Guidelines

1. At design time, set the the RunPromptBehavior of the Connection object to 4-adPromptNever. (Select the Connection object and press F4 to display the Properties window.)

2. At run time, set the dynamic prompt property of your connection to adPromptNever prior to opening your connection, as shown below:

DataEnvironment1.Connection1.Properties("Prompt") = adPromptNever
DataEnvironment1.Connection1.Open

Important Not all OLE DB Providers and ODBC Drivers support suppressing the prompt if login fails. And not all database management systems support the two-phase commit protocol required to support an
MTS transaction.

Using the DataReport with the DataEnvironment Object

When the DataReport is displayed for the first time, it must read the contents of the recordset. Once it has read the contents of the recordset, it leaves the recordset at BOF. Since this work is done
asynchronously, you can't simply reset the bookmark after invoking the Show method. There is no event to signify when the DataReport has finished reading the recordset. This situation also affects the
DataEnviroment because you may want to display the same data on a form and in a DataReport. If you display the data in textboxes on the form and then have a command button to display/print the data via
the DataReport, the textboxes will be blank because the textboxes are using the same recordset as the DataReport whose bookmark is currently at BOF. See the Knowledge Base article Q190607 for more
information.

Using the HFlexGrid Control with the DataEnvironment Object

The behavior of the Hierarchical FlexGrid differs from that of the DataGrid. While both are data-aware controls, the HFlexGrid control does not allow the user to edit data and propagate the changes back to the
database. Instead the data is read into the grid once. Once the data is displayed, the control no longer acts like a bound control. Navigating through the recordset does not affect the active row in the
MSHFlexGrid, and vice versa. Changes made to the recordset (insertions, updates, deletions, requeries) do not affect the MSHFlexGrid.

Working with Shape Commands

There are two distinct methods for requerying a database:

1. Requery using a Shape command.

2. Requery using a SQL statement.

The differences may account for some confusion when trying to program the DataEnvironment object.

Shape Commands Described

When you create a hierarchical recordset (adding Child commands and using the Relationship tab of the Properties dialog box to associate them), you are actually creating several recordsets. The resultant
family of recordsets cannot easily be duplicated by using a standard SQL statement. In fact, the Data Environment designer uses a different language syntax called the Shape command. You can see the Shape
command of any hierarchical recordset by checking the Source property either at run time or at design time:

1. Right-click the top-most Command object in a hierarchy.

2. Click Hierarchy Info.

3. By default, the Shape command is visible. An example is shown below:

SHAPE {SELECT * FROM `Customers`} AS Customers APPEND (( SHAPE {SELECT * FROM `Orders`} AS Orders APPEND ({SELECT * FROM 'Order Details`} AS OrderDetails RELATE 'OrderID' TO 'OrderID') AS OrderDetails) AS Orders RELATE 'CustomerID' TO
'CustomerID') AS Orders

You can reproduce the hierarchical recordset by assigning the Source property to the Shape command. However, as shown above, you must rebind the controls to the proper recordset objects. An example is
shown below:

With grdData
' Be sure to reset the DataMember property to the name of the
' Command object you want to bind to.
.DataMember = "Orders"
Set .DataSource = deNwind
End With

With txtCustomer
.DataMember = "Customers"
.DataField = "CompanyName"
Set .DataSource = deNwind
End With

Walking Through the Command Shape

A hierarchical recordset consists of several recordsets presented in a stair-like, parent-child structure. In the Data Environment, each recordset is created by a child Command. To "walk" the structure in code,
you must declare an ADO Recordset object variable for each child recordset and assign a reference to it. The reference must be to the Value property of a Field object that links two tables. In that case, note that
the Value property returns an object reference to the recordset:

Dim rsTop As ADODB.Recordset


Dim rsChild1 As ADODB.Recordset, rsChild2 As ADODB.Recordset
' Open the recordset.
DataEnvironment1.titleauthors
' Set rsTop to the topmost Command object.
Set rsTop = DataEnvironment1.rstitleauthors
' Set the first child object variable to the Value property of the
' Field named authors.
Set rsChild1 = rsX.Fields("authors").Value
' Set the second (grandchild) object variable.
' Note that we use the reference to the child recordset (rsChild1).
Set rsChild2 = rsChild1.Fields("titles").Value

http://msdn.microsoft.com/library/en-us/vbcon98/...aEnvironmentProgrammingGuidelines.asp?frame=true (3 of 4) [11/17/2002 11:12:58 PM]


Data Environment Programming Guidelines
You can also determine if the Field object's Value property returns a reference to a child recordset by checking if its Type property returns adChapter, as shown in the example below:

Dim f As Field, f2 As Field


Dim rs2 As Recordset
DataEnvironment1.Command1
Set rs2 = DataEnvironment1.rsCommand1.Fields("Command2").Value
For Each f In rs2.Fields
Debug.Print f.Name
If f.Type = adChapter Then
For Each f2 In f.Value.Fields
Debug.Print , f2.Name
Next f2
End If
Next f

After assigning references to the child recordsets to the object variables, you can then bind controls to the recordset objects.

Handling Events

After configuring a DataEnvironment object as a hierarchical recordset, it's logical to examine the code editor and check for the events for each of the objects in the hierarchy. However you will find that only the
topmost Command object has a set of ADO Recordset object events (WillMove, WillChangeField, MoveComplete, etc.). The question then becomes how to program the events for objects which don't exist.

Instead of declaring the object variables within the procedure (as shown above), declare them in the Declarations section of the code editor using the Private (or Public) and WithEvents keywords. Consequently
the events for the ADO Recordset object will become available for programming, as shown below:

Option Explicit
Private WithEvents rsChild1 As Recordset
Private WithEvents rsChild2 As Recordset

Private Sub BindRecordsets()


DataEnvironment1.titleauthors ' Open recordset.
Set rsTop = DataEnvironment1.rstitleauthors
Set rsChild1 = rsX.Fields("authors").Value
Set rsChild2 = rsChild1.Fields("titles").Value
' Bind the child recordsets to two DataGrid controls.
Set DataGrid1.DataSource = rsChild1
Set DataGrid1.DataSource = rsChild2
End Sub

Private rsChild1_WillMove(ByVal adReason As ADODB.EventReasonEnum, adStatus As ADODB.EventStatusEnum, ByVal pRecordset As ADODB.Recordset)


Debug.Print pRecordset!OrderDate
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/...aEnvironmentProgrammingGuidelines.asp?frame=true (4 of 4) [11/17/2002 11:12:58 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Data Environment Programming Guidelines

See Also

Up One Level The Data Environment designer allows the quick and easy building of hierarchical recordsets at design time. Programming the resulting DataEnvironment object, however, requires a
knowledge of the ADO programming model combined with characteristics of hierarchical recordsets. Below are the major points to visit when programming the DataEnvironment object.
Designing a DataEnvironment Object
Connection Objects Note The phrase "Data Environment designer" refers to the designer and its features. The phrase "DataEnvironment object" refers to the resulting programming object of the Data
Command Objects Environment designer.

Command Hierarchies
Requerying the Recordset
Field Mapping
Manipulating Your Data Environment Requerying a DataEnvironment-built recordset presents a few issues to be aware of. If you are using controls that are bound to the DataEnvironment, you must rebind those controls after
Attaching Code to ADO Events requerying the recordset. You can rebind the controls on a form to the DataEnvironment object by setting the DataMember, DataSource, and DataField properties wherever applicable.

Using a Data Environment with Your Application


Data Environment Programming Guidelines
Rebind After Using Requery Method
The Data Environment Extensibility Object Model
Scenarios For Using the Data Environment Designer Whenever you query the database using the Requery method, you must rebind the controls to the appropriate recordset objects, as shown in the example below:

deNwind.rsCustomers.Requery
' Rebind a TextBox control named txtCustomer and a DataGrid
' control named grdData.
With txtCustomer
Set .DataSource = deNwind
.DataMember = "Customers"
.DataField = "CompanyName"
End With
With grdData
.DataMember = "customers"
Set .DataSource = deNwind
End With

Note The Data Environment designer automatically prepends references to Command objects with "rs"—thus Customers becomes rsCustomers. Also notice that the DataEnvironment object
contains a "Customers" method. By invoking the method, you can open its recordset.

Closing and Reopening the Recordset

When you close a recordset, the controls bound to that recordset no longer listen for events broadcasted by that recordset to notify them of changes. If you reopen the recordset, the data for
that recordset will not appear in the controls until you rebind them.

Creating a Parameterized Query


The example below demonstrates how to create a parameterized query with the Data Environment designer.

To create a parameterized query

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDataEnvironmentProgrammingGuidelines.asp (1 of 5) [11/17/2002 11:13:01 PM]


Welcome to the MSDN Library

1. Create a new project and add a Data Environment designer to the project.

2. On the Data Environment designer, create a Connection object and configure it to connect to the SQL Server Pubs database.

3. Right-click the Connection object and click Add Command.

4. Rename the Command object CommandQuery.

5. Right-click the Command object and click Properties.

6. On the General tab, click SQL Statement and type the following parameterized query:

SELECT * FROM Authors Where Au_ID = ?

7. Click the Parameters tab. (A message will appear informing you that not enough information has been supplied. Click OK.)

A new Input parameter will have been created for you. You can create further parameters, if needed, or set properties of the parameter. If you are using the Access OLE DB Provider or ODBC Driver, see the section below entitled "Paramaterized Queries and
the Access OLE DB Provider and ODBC Driver."

8. Click OK to close the dialog box.

9. On the default form, draw two TextBox controls and a CommandButton control.

10. Add the code below to the Form object's code window:

Option Explicit
Private Sub Command1_Click()
' You must close the recordset before changing the parameter.
If DataEnvironment1.rsCommandQuery.State = adStateOpen Then
DataEnvironment1.rsCommandQuery.Close
End If
' Reopen the recordset with the input parameter supplied by
' the TextBox control.
DataEnvironment1.CommandQuery Text1.Text
With Text2
.DataField = "AU_LName"
.DataMember = "CommandQuery"
Set .DataSource = DataEnvironment1
End With
End Sub

Private Sub Form_Load()


' Supply a default value.
Text1.Text = "172-32-1172"
' Change the CommandButton caption.
Command1.Caption = "Run Query"
End Sub

11. Run the project and click the button. Change the text in Text1 to run another query.

Parameterized Queries At Run Time

It's possible to build a parameterized query with the Data Environment designer and have controls bound to that DataMember. That query will run when the form is loaded. If you don't have
the value of the parameter set ahead of time, the query will fail. You'll have a closed recordset and you'll need to re-bind your controls before explicitly running the query. To avoid this, at
design time be sure to supply a default value for the parameter (on the Parameters tab). Alternatively, at run time, simply make sure you call the Command explicitly before displaying a
control bound to that Command.

Paramaterized Queries and the Access OLE DB Provider and ODBC Driver

Due to limitations of the Microsoft® Access OLE DB provider and ODBC driver, parameterized queries are not fully supported in the Data Environment when connecting to an Access database,
because the driver and provider do not return information about parameters (like data type and direction) in the query.

Setting the Required Property for Stored Procedure Parameters


When running stored procedures from the DataEnvironment, how the Required property of a parameter is set depends on whether or not the stored procedure command is a child command in
a hierarchy.

Stored Procedure as Child Commands: Optional Parameters Only

Although it's possible to insert a stored procedure into a hierarchy as a child command, there are two conditions that must be met:

● The stored procedure must not have any required parameters.

● After inserting the stored procedure into a hierarchy, you must set the Required check box for any parameters to False.

To create a stored procedure as a child command

1. Right-click an existing Command object and click Add Child Command.

2. Right-click the new Command object and click Properties.

3. By default, the Database Object is set to Stored Procedure. Click the Object Name box to see a list of stored procedures and select one.

4. Click the Parameters tab.

5. Select any parameter except RETURN_VALUE.

6. Set the Required property to False.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDataEnvironmentProgrammingGuidelines.asp (2 of 5) [11/17/2002 11:13:01 PM]


Welcome to the MSDN Library

Setting Required Parameters for Inserted Stored Procedures with SQLServer


Required

When using SQLServer and stored procedures, it's possible to create stored procedures that have optional parameters. However, if the stored procedure is not a child object in a hierarchy,
optional parameters are not accepted, and instead must be supplied by your code.

An example of a stored procedure with an optional parameter (@idCol) is shown below:

CREATE PROCEDURE OptionalParametersNotAllowed


(@IDCol smallint = NULL)
AS
IF @IDCol = NULL
select count(SupplierID) from Products
ELSE
select count(SupplierID) from Products where SupplierID= @IDCol

With the Data Environment designer, you can insert the stored procedure by right-clicking a Connection object and clicking Insert Stored Procedures. As shown above, you can set properties of
the stored procedure's parameters by right-clicking the resulting Command object, clicking Properties, then clicking the Parameters tab. While it's possible to set the Required option for the
parameter to False, the DataEnvironment object will generate an error message ("Argument not optional") unless a value is supplied. To work around this situation, be sure to supply a value
as shown in the code below:

Private Sub Command1_Click()


' Open the connection.
DE.Connection1.Open , "sa"
' Run the stored procedure with a value.
DE.dbo_ OptionalParametersNotAllowed 8
Debug.Print DE.rsdbo_OptionalParametersNotAllowed.Fields(0).Value
' Free resources
DE.Connection1.Close
Set DE = Nothing
End Sub

Enabling the MTS SetAbort Method

If you use your DataEnvironment object in an MTS component with its default settings, the work done by the DataEnvironment is not in the MTS transaction. Thus the SetAbort method will not
roll back the work done by the DataEnvironment object. To ensure that the SetAbort method will roll back the DataEnvironment work, there are two methods:

1. At design time, set the the RunPromptBehavior of the Connection object to 4-adPromptNever. (Select the Connection object and press F4 to display the Properties window.)

2. At run time, set the dynamic prompt property of your connection to adPromptNever prior to opening your connection, as shown below:

DataEnvironment1.Connection1.Properties("Prompt") = adPromptNever
DataEnvironment1.Connection1.Open

Important Not all OLE DB Providers and ODBC Drivers support suppressing the prompt if login fails. And not all database management systems support the two-phase commit protocol
required to support an MTS transaction.

Using the DataReport with the DataEnvironment Object

When the DataReport is displayed for the first time, it must read the contents of the recordset. Once it has read the contents of the recordset, it leaves the recordset at BOF. Since this work is
done asynchronously, you can't simply reset the bookmark after invoking the Show method. There is no event to signify when the DataReport has finished reading the recordset. This situation
also affects the DataEnviroment because you may want to display the same data on a form and in a DataReport. If you display the data in textboxes on the form and then have a command
button to display/print the data via the DataReport, the textboxes will be blank because the textboxes are using the same recordset as the DataReport whose bookmark is currently at BOF.
See the Knowledge Base article Q190607 for more information.

Using the HFlexGrid Control with the DataEnvironment Object

The behavior of the Hierarchical FlexGrid differs from that of the DataGrid. While both are data-aware controls, the HFlexGrid control does not allow the user to edit data and propagate the
changes back to the database. Instead the data is read into the grid once. Once the data is displayed, the control no longer acts like a bound control. Navigating through the recordset does not
affect the active row in the MSHFlexGrid, and vice versa. Changes made to the recordset (insertions, updates, deletions, requeries) do not affect the MSHFlexGrid.

Working with Shape Commands

There are two distinct methods for requerying a database:

1. Requery using a Shape command.

2. Requery using a SQL statement.

The differences may account for some confusion when trying to program the DataEnvironment object.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDataEnvironmentProgrammingGuidelines.asp (3 of 5) [11/17/2002 11:13:01 PM]


Welcome to the MSDN Library

Shape Commands Described

When you create a hierarchical recordset (adding Child commands and using the Relationship tab of the Properties dialog box to associate them), you are actually creating several recordsets.
The resultant family of recordsets cannot easily be duplicated by using a standard SQL statement. In fact, the Data Environment designer uses a different language syntax called the Shape
command. You can see the Shape command of any hierarchical recordset by checking the Source property either at run time or at design time:

1. Right-click the top-most Command object in a hierarchy.

2. Click Hierarchy Info.

3. By default, the Shape command is visible. An example is shown below:

SHAPE {SELECT * FROM `Customers`} AS Customers APPEND (( SHAPE {SELECT * FROM `Orders`} AS Orders APPEND ({SELECT * FROM 'Order Details`} AS OrderDetails
RELATE 'OrderID' TO 'OrderID') AS OrderDetails) AS Orders RELATE 'CustomerID' TO 'CustomerID') AS Orders

You can reproduce the hierarchical recordset by assigning the Source property to the Shape command. However, as shown above, you must rebind the controls to the proper recordset objects.
An example is shown below:

With grdData
' Be sure to reset the DataMember property to the name of the
' Command object you want to bind to.
.DataMember = "Orders"
Set .DataSource = deNwind
End With

With txtCustomer
.DataMember = "Customers"
.DataField = "CompanyName"
Set .DataSource = deNwind
End With

Walking Through the Command Shape

A hierarchical recordset consists of several recordsets presented in a stair-like, parent-child structure. In the Data Environment, each recordset is created by a child Command. To "walk" the
structure in code, you must declare an ADO Recordset object variable for each child recordset and assign a reference to it. The reference must be to the Value property of a Field object that
links two tables. In that case, note that the Value property returns an object reference to the recordset:

Dim rsTop As ADODB.Recordset


Dim rsChild1 As ADODB.Recordset, rsChild2 As ADODB.Recordset
' Open the recordset.
DataEnvironment1.titleauthors
' Set rsTop to the topmost Command object.
Set rsTop = DataEnvironment1.rstitleauthors
' Set the first child object variable to the Value property of the
' Field named authors.
Set rsChild1 = rsX.Fields("authors").Value
' Set the second (grandchild) object variable.
' Note that we use the reference to the child recordset (rsChild1).
Set rsChild2 = rsChild1.Fields("titles").Value

You can also determine if the Field object's Value property returns a reference to a child recordset by checking if its Type property returns adChapter, as shown in the example below:

Dim f As Field, f2 As Field


Dim rs2 As Recordset
DataEnvironment1.Command1
Set rs2 = DataEnvironment1.rsCommand1.Fields("Command2").Value
For Each f In rs2.Fields
Debug.Print f.Name
If f.Type = adChapter Then
For Each f2 In f.Value.Fields
Debug.Print , f2.Name
Next f2
End If
Next f

After assigning references to the child recordsets to the object variables, you can then bind controls to the recordset objects.

Handling Events

After configuring a DataEnvironment object as a hierarchical recordset, it's logical to examine the code editor and check for the events for each of the objects in the hierarchy. However you will
find that only the topmost Command object has a set of ADO Recordset object events (WillMove, WillChangeField, MoveComplete, etc.). The question then becomes how to program the events
for objects which don't exist.

Instead of declaring the object variables within the procedure (as shown above), declare them in the Declarations section of the code editor using the Private (or Public) and WithEvents
keywords. Consequently the events for the ADO Recordset object will become available for programming, as shown below:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDataEnvironmentProgrammingGuidelines.asp (4 of 5) [11/17/2002 11:13:01 PM]


Welcome to the MSDN Library

Option Explicit
Private WithEvents rsChild1 As Recordset
Private WithEvents rsChild2 As Recordset

Private Sub BindRecordsets()


DataEnvironment1.titleauthors ' Open recordset.
Set rsTop = DataEnvironment1.rstitleauthors
Set rsChild1 = rsX.Fields("authors").Value
Set rsChild2 = rsChild1.Fields("titles").Value
' Bind the child recordsets to two DataGrid controls.
Set DataGrid1.DataSource = rsChild1
Set DataGrid1.DataSource = rsChild2
End Sub

Private rsChild1_WillMove(ByVal adReason As ADODB.EventReasonEnum, adStatus As ADODB.EventStatusEnum, ByVal


pRecordset As ADODB.Recordset)
Debug.Print pRecordset!OrderDate
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDataEnvironmentProgrammingGuidelines.asp (5 of 5) [11/17/2002 11:13:01 PM]


The Data Environment Extensibility Object Model

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

Visual Basic Concepts

The Data Environment Extensibility Object Model

See Also

Using the Data Environment Extensibility Object Model you can programmatically manipulate your DataEnvironment object at design time. Extensibility is the capacity to extend the function of the
development environment, thereby adding something to it that didn't exist there before. The Data Environment has an easy-to-understand modular system for customizing its environment
through a programming interface known as the Extensibility Object Model. Using this model you can create add-in extensions to the Visual Basic Integrated Development Environment (IDE).

All functionality that is available through the Data Environment designer's user interface is also available through its Extensibility Object Model.

To prevent the display of user interface when using the Extensibility Object Model to add and delete objects, you must set the option properties directly from the Data Environment. For example,
to ensure that no deletion confirmation user interface appears, set the PromptDelete property of the DataEnvironment object to False.

Note This example changes the confirmation setting for all DataEnvironment objects on your system and is not automatically reset. Therefore, you should return this to its default setting when
complete.

Before you can use the Data Environment Extensibility Object Model, you must reference it in Visual Basic.

To reference the Data Environment Extensibility Object Model

1. On the Project menu in Visual Basic, click References.

2. From the References dialog box, select Microsoft Data Environment Extensibility Objects 1.0, and then click OK.

When using the Extensibility Object Model, the DesignerID of the Data Environment designer is DEDesigner.DataEnvironment, and the object reference is DEExtDesigner.

All Data Environment methods, objects, and properties available to you through the Extensibility Object Model are documented in the Visual Basic Language Reference. See the DEExtDesigner
Object.

Using Your Data Environment in an Add-in

By using the Extensibility Object Model you can use your Data Environment in an add-in. The add-in can be:

● A wizard to create a DataEnvironment object and automatically bind it to a form.

● An alternative interface (other than the Data Environment) to create and modify DataEnvironment objects.

● A means to programmatically obtain information about an existing DataEnvironment object.

● A way to programmatically create a hierarchical set of Command objects using properties, and then obtain the ShapeText property to obtain the valid SHAPE Command generated by the DataEnvironment object.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconDEExtensObjectModel.asp?frame=true [11/17/2002 11:13:20 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

The Data Environment Extensibility Object Model

See Also

Up One Level Using the Data Environment Extensibility Object Model you can programmatically manipulate your DataEnvironment object at design time. Extensibility is the capacity to extend the function of
the development environment, thereby adding something to it that didn't exist there before. The Data Environment has an easy-to-understand modular system for customizing its environment
Designing a DataEnvironment Object through a programming interface known as the Extensibility Object Model. Using this model you can create add-in extensions to the Visual Basic Integrated Development Environment (IDE).

Connection Objects
Command Objects All functionality that is available through the Data Environment designer's user interface is also available through its Extensibility Object Model.

Command Hierarchies
Field Mapping To prevent the display of user interface when using the Extensibility Object Model to add and delete objects, you must set the option properties directly from the Data Environment. For
example, to ensure that no deletion confirmation user interface appears, set the PromptDelete property of the DataEnvironment object to False.
Manipulating Your Data Environment
Attaching Code to ADO Events
Note This example changes the confirmation setting for all DataEnvironment objects on your system and is not automatically reset. Therefore, you should return this to its default setting
Using a Data Environment with Your Application when complete.

Data Environment Programming Guidelines


The Data Environment Extensibility Object Model Before you can use the Data Environment Extensibility Object Model, you must reference it in Visual Basic.

Scenarios For Using the Data Environment Designer


To reference the Data Environment Extensibility Object Model

1. On the Project menu in Visual Basic, click References.

2. From the References dialog box, select Microsoft Data Environment Extensibility Objects 1.0, and then click OK.

When using the Extensibility Object Model, the DesignerID of the Data Environment designer is DEDesigner.DataEnvironment, and the object reference is DEExtDesigner.

All Data Environment methods, objects, and properties available to you through the Extensibility Object Model are documented in the Visual Basic Language Reference. See the DEExtDesigner
Object.

Using Your Data Environment in an Add-in

By using the Extensibility Object Model you can use your Data Environment in an add-in. The add-in can be:

● A wizard to create a DataEnvironment object and automatically bind it to a form.

● An alternative interface (other than the Data Environment) to create and modify DataEnvironment objects.

● A means to programmatically obtain information about an existing DataEnvironment object.

● A way to programmatically create a hierarchical set of Command objects using properties, and then obtain the ShapeText property to obtain the valid SHAPE Command generated by the DataEnvironment object.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDEExtensObjectModel.asp (1 of 2) [11/17/2002 11:13:22 PM]


Welcome to the MSDN Library
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDEExtensObjectModel.asp (2 of 2) [11/17/2002 11:13:22 PM]


Scenarios For Using the Data Environment Designer

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

Visual Basic Concepts

Scenarios For Using the Data Environment Designer

See Also

This section presents scenarios that illustrate how you can use the Data Environment designer. Among the features highlighted are creating a hierarchy, adding aggregates, grouping, and binding
to a Hierarchical FlexGrid.

Creating a Relation Hierarchy Between a Customer and an Order Table

To create a relation hierarchy between a Customer and an Order table

1. Create Command object, connected to the Northwind database.

2. Select the Customers table as the Command object's source. Change the Command object name to "Customers."

3. Create a child Command off the Customer Command object. Select the Orders table as the child's source. Change the child Command object's name to "Orders."

4. Click the Relation tab, and then link the parent and child Command objects using their CustomerID fields.

To view the results, see "Binding Your Data Environment to a Hierarchical FlexGrid Control" later in this topic.

Adding an Aggregate to the Customer Command Object

To add an aggregate to the Customer Command object to obtain the SUM of the order amounts for all orders per customer

1. Edit the Customer Command object's properties.

2. Click the Aggregate tab, and then click Add.

3. Name the aggregate "OrdersTotal."

4. Select Sum as the function.

5. Select the Aggregate On item "Orders".

6. Select OrderID as the Field to Sum.

The OrdersTotal aggregate is added to the DataEnvironment object as a new Field object. At run time, the OrdersTotal aggregate will contain a calculated value for each customer.

To view the results, see "Binding Your Data Environment to a Hierarchical FlexGrid Control" later in this topic.

Grouping the Customer Command Object by State

To group the customer Command object by state

1. Edit the Customer Command object's properties.

2. Click the Grouping tab, and select Group Command Object.

3. Name the grouping Command object "ByCountry."

4. Select "Country" from the Fields in Command list, and then click > to move it into the Fields Used for Grouping list.

An additional Recordset object, ByCountry, is exposed on top of the Customers Command object. When binding to the Hierarchical FlexGrid, you should bind to the ByCountry Recordset, not to the
Customers Command object.

To view the results, see "Binding Your Data Environment to a Hierarchical FlexGrid Control" later in this topic.

Adding an Aggregate to Count the Number of Customers per State

To add an aggregate to count the number of customers per state

1. Edit the Customer Command object's properties.

2. Click the Aggregates tab, and click Add.

3. Name the aggregate "CustCount."

4. Select Count as the function.

5. Select the Aggregate On item "Grouping".

6. Select CustID as the Field to Count.

Another field is added to the summary (grouping) Command object. This Field object contains a calculated value that counts the number of customers per state.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconUserScenariosForDE.asp?frame=true (1 of 2) [11/17/2002 11:13:27 PM]


Scenarios For Using the Data Environment Designer

To view the results, see "Binding Your Data Environment to a Hierarchical FlexGrid Control" later in this topic.

Adding a Grand Total Aggregate to Count the Number of States with Customers

To add a Grand Total Aggregate to count the number of states with customers

1. Edit the Customer Command object's properties.

2. Click the Aggregates tab, and then click Add.

3. Name the aggregate "NumStatesWithCustomers."

4. Select Count as the function.

5. Select GrandTotal as the Aggregate On item.

6. Select the "State" as the Field.

7. Name the Grand Total "CustomerGrandTotal."

An additional Recordset object, NumStatesWithCustomers, is exposed on top of the Customers Command object. This new object contains the number of states that have customers.

To view the results, see the following section.

Binding Your Data Environment to a Hierarchical FlexGrid Control

The following scenario is provided so you can view the results of the previous scenarios. See the Hierarchical FlexGrid Control for more information.

To bind your Data Environment to a Hierarchical FlexGrid control

1. Once you have completed the previous Data Environment scenarios, drag an MSHFlexGrid control onto a Visual Basic form.

2. From the Visual Basic property sheet, set the DataSource property to the DataEnvironment object that contains the Command object that you want to bind to the Hierarchical FlexGrid control. For example, specify DataEnvironment1.

3. From the Visual Basic Properties window, set the DataMember property to a parent Command object in your Data Environment. Your data is now bound to a Hierarchical FlexGrid control.

4. To view the data in the Hierarchical FlexGrid, select Start from the Run menu or press F5. The structure is retrieved and displays in the Hierarchical FlexGrid.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconUserScenariosForDE.asp?frame=true (2 of 2) [11/17/2002 11:13:27 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Scenarios For Using the Data Environment Designer

See Also

Up One Level This section presents scenarios that illustrate how you can use the Data Environment designer. Among the features highlighted are creating a hierarchy, adding aggregates, grouping, and
binding to a Hierarchical FlexGrid.
Designing a DataEnvironment Object
Connection Objects Creating a Relation Hierarchy Between a Customer and an Order Table
Command Objects
Command Hierarchies To create a relation hierarchy between a Customer and an Order table

Field Mapping
Manipulating Your Data Environment 1. Create Command object, connected to the Northwind database.

2. Select the Customers table as the Command object's source. Change the Command object name to "Customers."
Attaching Code to ADO Events 3. Create a child Command off the Customer Command object. Select the Orders table as the child's source. Change the child Command object's name to "Orders."

Using a Data Environment with Your Application 4. Click the Relation tab, and then link the parent and child Command objects using their CustomerID fields.

Data Environment Programming Guidelines


To view the results, see "Binding Your Data Environment to a Hierarchical FlexGrid Control" later in this topic.
The Data Environment Extensibility Object Model
Scenarios For Using the Data Environment Designer
Adding an Aggregate to the Customer Command Object

To add an aggregate to the Customer Command object to obtain the SUM of the order amounts for all orders per customer

1. Edit the Customer Command object's properties.

2. Click the Aggregate tab, and then click Add.

3. Name the aggregate "OrdersTotal."

4. Select Sum as the function.

5. Select the Aggregate On item "Orders".

6. Select OrderID as the Field to Sum.

The OrdersTotal aggregate is added to the DataEnvironment object as a new Field object. At run time, the OrdersTotal aggregate will contain a calculated value for each customer.

To view the results, see "Binding Your Data Environment to a Hierarchical FlexGrid Control" later in this topic.

Grouping the Customer Command Object by State

To group the customer Command object by state

1. Edit the Customer Command object's properties.

2. Click the Grouping tab, and select Group Command Object.

3. Name the grouping Command object "ByCountry."

4. Select "Country" from the Fields in Command list, and then click > to move it into the Fields Used for Grouping list.

An additional Recordset object, ByCountry, is exposed on top of the Customers Command object. When binding to the Hierarchical FlexGrid, you should bind to the ByCountry Recordset, not to
the Customers Command object.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUserScenariosForDE.asp (1 of 2) [11/17/2002 11:13:29 PM]


Welcome to the MSDN Library

To view the results, see "Binding Your Data Environment to a Hierarchical FlexGrid Control" later in this topic.

Adding an Aggregate to Count the Number of Customers per State

To add an aggregate to count the number of customers per state

1. Edit the Customer Command object's properties.

2. Click the Aggregates tab, and click Add.

3. Name the aggregate "CustCount."

4. Select Count as the function.

5. Select the Aggregate On item "Grouping".

6. Select CustID as the Field to Count.

Another field is added to the summary (grouping) Command object. This Field object contains a calculated value that counts the number of customers per state.

To view the results, see "Binding Your Data Environment to a Hierarchical FlexGrid Control" later in this topic.

Adding a Grand Total Aggregate to Count the Number of States with Customers

To add a Grand Total Aggregate to count the number of states with customers

1. Edit the Customer Command object's properties.

2. Click the Aggregates tab, and then click Add.

3. Name the aggregate "NumStatesWithCustomers."

4. Select Count as the function.

5. Select GrandTotal as the Aggregate On item.

6. Select the "State" as the Field.

7. Name the Grand Total "CustomerGrandTotal."

An additional Recordset object, NumStatesWithCustomers, is exposed on top of the Customers Command object. This new object contains the number of states that have customers.

To view the results, see the following section.

Binding Your Data Environment to a Hierarchical FlexGrid Control

The following scenario is provided so you can view the results of the previous scenarios. See the Hierarchical FlexGrid Control for more information.

To bind your Data Environment to a Hierarchical FlexGrid control

1. Once you have completed the previous Data Environment scenarios, drag an MSHFlexGrid control onto a Visual Basic form.

2. From the Visual Basic property sheet, set the DataSource property to the DataEnvironment object that contains the Command object that you want to bind to the Hierarchical FlexGrid control. For example, specify DataEnvironment1.

3. From the Visual Basic Properties window, set the DataMember property to a parent Command object in your Data Environment. Your data is now bound to a Hierarchical FlexGrid control.

4. To view the data in the Hierarchical FlexGrid, select Start from the Run menu or press F5. The structure is retrieved and displays in the Hierarchical FlexGrid.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUserScenariosForDE.asp (2 of 2) [11/17/2002 11:13:29 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)

MSDN Library GO
Advanced Search Visual Basic Concepts

Writing Reports with the Microsoft Data Report Designer

See Also

Up One Level The Microsoft Data Report designer is a versatile data report generator that features the ability to created banded hierarchical reports. Used in conjunction with a data source such as the Data
Environment designer, you can create reports from several different relational tables. In addition to creating printable reports, you can also export the report to HTML or text files.
Parts of the Data Report
Creating a Simple Data Report Possible Uses
Exporting a Data Report
Printing the Data Report ● Automatically create reports that are exported in HTML format for instant distribution on the Internet.

Create reports that show the sums of transactions occurring on a daily basis.
Data Report Events

Understanding Control Placement on the Data Report Designer Data Report Designer Features

The Data Report designer has several features:

1. Drag-and-Drop Functionality for Fields—Drag fields from the Microsoft Data Environment designer to the Data Report designer. When you do this, Visual Basic automatically creates a text box control on the data report and sets the DataMember and
DataField properties of the dropped field. You can also drag a Command object from the Data Environment designer to the Data Report designer. In that case, for each of the fields contained by the Command object, a text box control will be created on the
data report; the DataMember and DataField property for each text box will be set to the appropriate values.

2. Toolbox Controls—The Data Report designer features its own set of controls. When a Data Report designer is added to a project, the controls are automatically created on a new Toolbox tab named DataReport. Most of the controls are functionally identical
to Visual Basic intrinsic controls, and include a Label, Shape, Image, TextBox, and Line control. The sixth control, the Function control, automatically generates one of four kinds of information: Sum, Average, Minimum, or Maximum. For more information
about the Function control, see "Adding a Function Control to the Data Report."

3. Print Preview—Preview the report by using the Show method. The data report is then generated and displayed in its own window.

Note A printer must be installed on the computer to show the report in print preview mode.

4. Print Reports—Print a report programmatically by calling the PrintReport method. When the data report is in preview mode, users can also print by clicking the printer icon on the toolbar.

Note A printer must be installed on the computer to print a report.

5. File Export—Export the data report information using the ExportReport method. Formats for export include HTML and text.

6. Export Templates—You can create a collection of file templates to be used with the ExportReport method. This is useful for exporting reports in a variety of formats, each tailored to the report type.

7. Asynchonous Operation—The DataReport object's PrintReport and ExportReport methods are asynchronous operations. Using the ProcessingTimeout event, you can monitor the state of these operations and cancel any that are taking too long.

Topics

● Parts of the Data Report

● Creating a Simple Data Report

● Exporting a Data Report

● Printing a Data Report

● Data Report Events

● Understanding Control Placement on the Data Report Designer

Sample Application

The sample application named prjNwind corresponds to the project built in the series of topics that begin with "Creating a Simple Data Report." If you have installed the Visual Basic sample
applications, the file can be found in the Samples directory. If you have not installed the sample applications, the file can be found on the MSDN™ CD that accompanies Visual Basic.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingMicrosoftDataReportDesigner.asp (1 of 2) [11/17/2002 11:14:22 PM]


Welcome to the MSDN Library
Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingMicrosoftDataReportDesigner.asp (2 of 2) [11/17/2002 11:14:22 PM]


Parts of the Data Report

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer

Visual Basic Concepts

Parts of the Data Report

See Also

The Data Report designer consists of the following objects:

1. DataReport object—Similar to a Visual Basic form, the DataReport object has both a visual designer and a code module. Use the designer to create the layout of a report. You can also add code to the designer's code module to programmatically format controls
or sections contained by the designer.

2. Section object—Each section of the Data Report designer is represented by a Section object in a Sections collection. At design time, each section is represented by a header that you can click to select the section, and the section's pane where you can place and
position controls. Use the object and its properties to dynamically reconfigure a report before it is built.

3. Data Report Controls—Special controls that only work on the Data Report designer are included with it. (Note: you cannot use Visual Basic's intrinsic controls, or any ActiveX controls, on the Data Report designer). These controls are found in the Visual Basic
Toolbox, but they are placed on a separate tab named "DataReport."

Sections of the Data Report Designer

The default Data Report designer contains these Sections:

● Report Header—contains the text that appears at the very beginning of a report, such as the report title, author, or database name. If you want the Report Header to be the first page in the report, set its ForcePageBreak property to rptPageBreakAfter.

● Page Header—contains information that goes at the top of every page, such as the report's title.

● Group Header/Footer—contains a "repeating" section of the data report. Each group header is matched with a group footer. The header and footer pair are associated with a single Command object in the Data Environment designer.

● Details—contains the innermost "repeating" part (the records) of the report. The details section is associated with the lowest-level Command object in a Data Environment hierarchy.

● Page Footer—contains the information that goes at the bottom of every page, such as the page number.

● Report Footer—contains the text that appears at the very end of the report, such as summary information, or an address or contact name. The Report Footer appears between the last Page Header and Page Footer.

Data Report Controls

When a new Data Report designer is added to a project, the following controls are automatically placed in the Toolbox tab named DataReport:

● TextBox Control (RptTextBox)—allows you to format text, or assign a DataFormat.

● Label Control (RptLabel)—allows you to place labels on the report to identify fields or sections.

● Image Control (RptImage)—enables you to place graphics on your report. Note that this control cannot be bound to a data field.

● Line Control (RptLine)—lets you draw rules on the report to further distinguish sections.

● Shape Control (RptShape)—enables you to place rectangles, triangles, or circles (and ovals) on a report.

● Function Control (RptFunction)—a special text box that calculates values as the report is generated.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconPartsOfDataReport.asp?frame=true [11/17/2002 11:14:31 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Parts of the Data Report

See Also

Up One Level The Data Report designer consists of the following objects:

Parts of the Data Report


Creating a Simple Data Report 1. DataReport object—Similar to a Visual Basic form, the DataReport object has both a visual designer and a code module. Use the designer to create the layout of a report. You can also add code to the designer's code module to programmatically format
controls or sections contained by the designer.

Exporting a Data Report 2. Section object—Each section of the Data Report designer is represented by a Section object in a Sections collection. At design time, each section is represented by a header that you can click to select the section, and the section's pane where you can place
and position controls. Use the object and its properties to dynamically reconfigure a report before it is built.

Printing the Data Report 3. Data Report Controls—Special controls that only work on the Data Report designer are included with it. (Note: you cannot use Visual Basic's intrinsic controls, or any ActiveX controls, on the Data Report designer). These controls are found in the Visual
Basic Toolbox, but they are placed on a separate tab named "DataReport."

Data Report Events


Sections of the Data Report Designer
Understanding Control Placement on the Data Report Designer
The default Data Report designer contains these Sections:

● Report Header—contains the text that appears at the very beginning of a report, such as the report title, author, or database name. If you want the Report Header to be the first page in the report, set its ForcePageBreak property to rptPageBreakAfter.

● Page Header—contains information that goes at the top of every page, such as the report's title.

● Group Header/Footer—contains a "repeating" section of the data report. Each group header is matched with a group footer. The header and footer pair are associated with a single Command object in the Data Environment designer.

● Details—contains the innermost "repeating" part (the records) of the report. The details section is associated with the lowest-level Command object in a Data Environment hierarchy.

● Page Footer—contains the information that goes at the bottom of every page, such as the page number.

● Report Footer—contains the text that appears at the very end of the report, such as summary information, or an address or contact name. The Report Footer appears between the last Page Header and Page Footer.

Data Report Controls

When a new Data Report designer is added to a project, the following controls are automatically placed in the Toolbox tab named DataReport:

● TextBox Control (RptTextBox)—allows you to format text, or assign a DataFormat.

● Label Control (RptLabel)—allows you to place labels on the report to identify fields or sections.

● Image Control (RptImage)—enables you to place graphics on your report. Note that this control cannot be bound to a data field.

● Line Control (RptLine)—lets you draw rules on the report to further distinguish sections.

● Shape Control (RptShape)—enables you to place rectangles, triangles, or circles (and ovals) on a report.

● Function Control (RptFunction)—a special text box that calculates values as the report is generated.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconPartsOfDataReport.asp [11/17/2002 11:14:32 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating a Simple Data Report

See Also

Up One Level This topic creates a simple data report using a Data Environment designer as a data source. The Data Environment designer uses the NorthWind database supplied with Visual Basic to create a
simple hierarchical cursor. The cursor contains two tables, Customers and Orders, and uses the CustomerID field to link the two. The finished report resembles the figure below.
Extending the Data Report
Adding a Calculated Field to the Data Report Simple Data Report: Order Dates by Customers
Adding a Function Control to the Data Report
Grouping Information in the Data Report
Adding an Aggregate Field to the Data Report
Forcing Page Breaks in the Data Report
Adding Date, Time, Page Number, and Title to the Data Report

Before you begin the step-by-step process, ensure that the Northwind database (Nwind.mdb) is present on your computer. If it is not present, copy the file from your Visual Basic CD onto
your hard disk.

To create a simple hierarchical cursor in the Data Environment designer

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingSimpleDataReport.asp (1 of 4) [11/17/2002 11:14:43 PM]


Welcome to the MSDN Library

1. Create a new Standard EXE project.

2. On the Project menu, click Add Data Environment to add a designer to your project. If the designer is not listed on the Project menu, click Components. Click the Designers tab, and click Data Environment to add the designer to the menu.

Note The first four kinds of ActiveX designers loaded for a project are listed on the Project menu. If more than four designers are loaded, the later ones will be available from the More ActiveX Designers submenu on the Project menu.

3. On the Data Link Properties dialog box, click Microsoft Jet 3.51 OLE DB Provider. This selects the correct OLE DB provider for accessing a Jet database.

4. Click the Next button to get to the Connection tab.

5. Click the ellipsis button (…) next to the first text box.

6. Use the Select Access Database dialog box to navigate to the nwind.mdb file, which is installed in the Program Files\Microsoft Visual Studio\Vb98 directory.

7. Click OK to close the dialog box.

8. Right-click the Connection1 icon, and click Rename. Change the name of the icon to Northwind.

9. Right-click the Northwind icon, and then click Add Command to display the Command1 dialog box. In the dialog box, set the properties as shown below:

Property Setting

Command Name Customers

Connection Northwind

DataBase Object Table

Object Name Customers

10. Click OK to close the dialog box.

11. Right-click the Customers command, and click Add Child Command to display the Command2 dialog box. In the dialog box, set the properties as shown below:

Property Setting

Command Name Orders

Connection Northwind

DataBase Object Table

Object Name Orders

12. Click the Relation tab. The Relate to a Parent Command Object check box should be checked. The Parent box should contain Customers; both the Parent Fields and Child Fields/Parameters boxes should contain CustomerID.

When designing relational databases, it's customary for related tables to use the same name for linking fields. In this case, the linking fields are both named CustomerID. The Data Environment designer automatically matches such pairs in the dialog box.

13. Click Add. Click OK to close the dialog box.

Clicking the Add button adds the relation to the Command object. After closing the dialog box, the Data Environment designer reflects the relationship by displaying the two commands as a hierarchy. This hierarchy will be used to create the data report.

14. Set the properties of the project and designer according to the settings below, then save the project:

Object Property Setting

Project Name prjNwind

DataEnvironment Name deNwind

Form Name frmShowReport

Creating the Data Report

Once the Data Environment designer has been created, you can create a data report. Because not all of the fields in the data environment will be useful in a report, this series of topics creates
a limited report that displays only a few fields.

To create a new data report

1. On the Project menu, click Add Data Report, and Visual Basic will add it to your project. If the designer is not on the Project menu, click Components. Click the Designers tab, and click Data Report to add the designer to the menu.

Note The first four kinds of ActiveX designers loaded for a project are listed on the Project menu. If more than four designers are loaded, the later ones will be available from the More ActiveX Designers submenu on the Project menu.

2. Set the properties of the DataReport object according to the table below:

Property Setting

Name rptNwind

Caption Northwind Data Report

3. On the Properties window, click DataSource and then click deNwind. Then click DataMember and click Customers.

Important To set the DataSource property to deNwind, the Data Environment designer must be open. If it is closed, press CTRL+R to display the Project window, then double-click the data environment icon.

4. Right-click the Data Report designer, and click Retrieve Structure.

You have added a new group section to the designer. Each group section has a one-to-one correspondence to a Command object in the data environment; in this case, the new Group section corresponds to the Customers Command object. Notice also that
the Group Header has a matching Group Footer section.

Note The Data Environment allows you to create hierarchies of Command objects wherein a Command object has more than one child object — child Command objects parallel to each other. The Data Report designer, however, is not as flexible, and can't
display more than one child object at a time. In such cases, when executing a Retrieve Structure command, the Data Report will display only the first of the child commands, and none below it. Thus you should avoid creating Command hierarchies with
parallel children commands.

5. From the Data Environment designer, drag the CompanyName field (under the Customers command) onto the Group Header (Customers_Header) section.

The Group Header section can contain any field from the Customers command, however, for demonstration purposes, only the Customer name is displayed at this time.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingSimpleDataReport.asp (2 of 4) [11/17/2002 11:14:43 PM]


Welcome to the MSDN Library
6. Delete the Label control (rptLabel) named Label1.

If you do not want a Label control to be included with the TextBox control, you can uncheck the Drag and Drop Fields Caption option on the Field Mapping tab of the Data Environment designer's Options dialog box.

7. From the Data Environment designer, drag the OrderDate field (under the Orders command) onto the Details (Orders_Detail) section. Delete the Label control.

The Details section represents the innermost "repeating" section, and thus corresponds to the lowest Command object in the Data Environment hierarchy: the Orders Command object.

8. Resize the Data Report designer's sections to resemble the figure below:

It's important to resize the height of the Details section to be as short as possible because the height will be multiplied for every OrderDate returned for the CompanyName. Any extra space below or above the OrderDate text box will result in unneeded
space in the final report.

9. Save the project.

Preview the Data Report Using the Show Method

Now that the data environment and the data report objects have been created, you are almost ready to run the project. One step remains: to write code to show the data report.

To show the data report at run time

1. On the Project Explorer window, double-click the frmShowReport icon to display the Form designer.

2. On Toolbox, click the General tab.

When you add a Data Report designer to your project, its controls are added to the tab named DataReport. To use the standard Visual Basic controls, you must switch to the General tab.

3. Click the CommandButton icon and draw a CommandButton on the form.

4. Set the properties of the Command1 control according to the table below:

Property Setting

Name cmdShow

Caption Show Report

5. In the button's Click event, paste the code below.

Private Sub cmdShow_Click()


rptNwind.Show
End Sub

6. Save and run the project.

7. Click Show Report to display the report in print preview mode.

Optional—Setting the Data Report as the Startup Object

You can also display the data report with no code at all.

1. On the Project menu, click prjNwind Properties.

2. In the Startup Object box, select rptNwind.

3. Save and run the project.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingSimpleDataReport.asp (3 of 4) [11/17/2002 11:14:43 PM]


Welcome to the MSDN Library
Note If you use this method, you can remove the Form object from your project.

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Extending the Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingSimpleDataReport.asp (4 of 4) [11/17/2002 11:14:43 PM]


Extending the Data Report

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

Visual Basic Concepts

Extending the Data Report

See Also

Once you have a simple data report, it's easy to extend it and make a more complex presentation. In the procedure below, the data environment is first extended with the Order Details and
Products tables. The extended report includes the names of products ordered on a specific date, and resembles the figure below.

Extended Data Report With Order Details

Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

To extend the data environment

1. On the Data Environment designer, right-click the Orders Command object. Then click Add Child Command.

2. On the Command1 Properties dialog box, set the following properties:

Property Setting

Command Name OrderDetails

Connection Northwind

DataBase Object Table

Object Name Order Details

3. Click the Relation tab. The Relate to a Parent Command Object check box should be checked. The Parent box should contain Orders; both the Parent Fields and Child Fields/Parameters boxes should contain OrderID. Click the Add button and then click

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconExtendingDataReport.asp?frame=true (1 of 3) [11/17/2002 11:14:46 PM]


Extending the Data Report
OK to close the dialog box.

4. Right-click the OrderDetails Command object, and click Add Child Command. Set the properties of the connection as shown below:

Property Setting

Command Name Products

Connection Northwind

DataBase Object Table

Object Name Products

5. Click the Relation tab. The Relate to a Parent Command Object check box should be checked. The Parent box should contain OrderDetails; both the Parent Fields and Child Fields/Parameters boxes should contain ProductID. Click the Add button and
then click OK to close the dialog box.

Extending the Data Report

Once the data environment has been extended with new tables, you can extend the data report as well by dragging fields from the Data Environment designer to the Data Report designer.

To Extend the data report

1. Right-click the Data Report designer, and clear Show Page Header/Footer box.

Clearing this option deletes the page header and footer, which are not being used at this point.

2. Right-click the Data Report designer, and click Insert Group Header/Footer. The Insert New Group Header/Footer dialog box will be displayed.

The dialog box allows you to determine if the new header and footer will "bracket" other header/footer pairs. This becomes important as you add more header and footer pairs because the outermost pair of header/footers subordinates all other pairs. This is
discussed in greater detail in "Parts of the Data Report."

3. Click OK to select the default placement of the new header and footer pair and close the dialog box.

4. Select the new group header, and on the Properties window, change its name from Section1 to Orders_Header. Change the corresponding footer name from Section4 to Orders_Footer.

5. Repeat steps 2 to 3. Name the new group header OrderDetails_Header, and the new group footer OrderDetails_Footer.

6. Click the Detail (Orders_Detail) section to select it. On the Properties window, change the section's name to Products_Detail.

7. Using the mouse, drag the OrderDate field from the Detail (Products_Detail) section to the Orders_Header section.

8. From the Data Environment designer, drag the ProductName field (under the Products command) into the Detail (Products_Detail) section.

9. Delete the Label control named Label1.

10. Resize the group headers, and rearrange the text box controls to resemble the figure below.

The figure above requires some explanation. First, the Group footers are all closed in order to take up the least possible space. Like the Details section, any additional space left in any header or footer will be multiplied in the final report. Therefore, if a header or
footer doesn't contain any fields, you can close the distance between the headers or footers.

The Group Header named OrderDetails_Header is also closed. If you wonder why no fields are being shown, you must understand that the Order Details table in the Northwind database is a join table—the table contains only the IDs of records from the Orders
table joined to IDs of records from the Products table. Thus the Order Details table doesn't contain fields which are actually displayed. Instead, it functions only to join two other tables. In the Data Report designer, the Order Details table therefore functions only to
create groups of records—the product names grouped under the order dates.

Finally, the Details section contains only the names of products. The Details section contains the innermost level of repeating records.

11. Save and run the project.

Step by Step

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconExtendingDataReport.asp?frame=true (2 of 3) [11/17/2002 11:14:46 PM]


Extending the Data Report

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Adding a Calculated Field to the Data Report

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconExtendingDataReport.asp?frame=true (3 of 3) [11/17/2002 11:14:46 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

MSDN Library GO
Advanced Search Visual Basic Concepts

Extending the Data Report

See Also

Up One Level Once you have a simple data report, it's easy to extend it and make a more complex presentation. In the procedure below, the data environment is first extended with the Order Details and
Products tables. The extended report includes the names of products ordered on a specific date, and resembles the figure below.
Extending the Data Report
Adding a Calculated Field to the Data Report Extended Data Report With Order Details
Adding a Function Control to the Data Report
Grouping Information in the Data Report
Adding an Aggregate Field to the Data Report
Forcing Page Breaks in the Data Report
Adding Date, Time, Page Number, and Title to the Data Report

Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconExtendingDataReport.asp (1 of 3) [11/17/2002 11:14:47 PM]


Welcome to the MSDN Library
To extend the data environment

1. On the Data Environment designer, right-click the Orders Command object. Then click Add Child Command.

2. On the Command1 Properties dialog box, set the following properties:

Property Setting

Command Name OrderDetails

Connection Northwind

DataBase Object Table

Object Name Order Details

3. Click the Relation tab. The Relate to a Parent Command Object check box should be checked. The Parent box should contain Orders; both the Parent Fields and Child Fields/Parameters boxes should contain OrderID. Click the Add button and
then click OK to close the dialog box.

4. Right-click the OrderDetails Command object, and click Add Child Command. Set the properties of the connection as shown below:

Property Setting

Command Name Products

Connection Northwind

DataBase Object Table

Object Name Products

5. Click the Relation tab. The Relate to a Parent Command Object check box should be checked. The Parent box should contain OrderDetails; both the Parent Fields and Child Fields/Parameters boxes should contain ProductID. Click the Add
button and then click OK to close the dialog box.

Extending the Data Report

Once the data environment has been extended with new tables, you can extend the data report as well by dragging fields from the Data Environment designer to the Data Report designer.

To Extend the data report

1. Right-click the Data Report designer, and clear Show Page Header/Footer box.

Clearing this option deletes the page header and footer, which are not being used at this point.

2. Right-click the Data Report designer, and click Insert Group Header/Footer. The Insert New Group Header/Footer dialog box will be displayed.

The dialog box allows you to determine if the new header and footer will "bracket" other header/footer pairs. This becomes important as you add more header and footer pairs because the outermost pair of header/footers subordinates all other pairs. This is
discussed in greater detail in "Parts of the Data Report."

3. Click OK to select the default placement of the new header and footer pair and close the dialog box.

4. Select the new group header, and on the Properties window, change its name from Section1 to Orders_Header. Change the corresponding footer name from Section4 to Orders_Footer.

5. Repeat steps 2 to 3. Name the new group header OrderDetails_Header, and the new group footer OrderDetails_Footer.

6. Click the Detail (Orders_Detail) section to select it. On the Properties window, change the section's name to Products_Detail.

7. Using the mouse, drag the OrderDate field from the Detail (Products_Detail) section to the Orders_Header section.

8. From the Data Environment designer, drag the ProductName field (under the Products command) into the Detail (Products_Detail) section.

9. Delete the Label control named Label1.

10. Resize the group headers, and rearrange the text box controls to resemble the figure below.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconExtendingDataReport.asp (2 of 3) [11/17/2002 11:14:47 PM]


Welcome to the MSDN Library

The figure above requires some explanation. First, the Group footers are all closed in order to take up the least possible space. Like the Details section, any additional space left in any header or footer will be multiplied in the final report. Therefore, if a
header or footer doesn't contain any fields, you can close the distance between the headers or footers.

The Group Header named OrderDetails_Header is also closed. If you wonder why no fields are being shown, you must understand that the Order Details table in the Northwind database is a join table—the table contains only the IDs of records from the
Orders table joined to IDs of records from the Products table. Thus the Order Details table doesn't contain fields which are actually displayed. Instead, it functions only to join two other tables. In the Data Report designer, the Order Details table therefore
functions only to create groups of records—the product names grouped under the order dates.

Finally, the Details section contains only the names of products. The Details section contains the innermost level of repeating records.

11. Save and run the project.

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Adding a Calculated Field to the Data Report

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconExtendingDataReport.asp (3 of 3) [11/17/2002 11:14:47 PM]


Adding a Calculated Field to the Data Report

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

Visual Basic Concepts

Adding a Calculated Field to the Data Report

See Also

A calculated field is a field whose value is calculated as the report is generated. For example, when estimating the tax on an order, you must multiply the total price by the local tax rate. But since
local tax rates differ and won't be stored in the database, the tax is generated as the report is created—a calculated field.

In this example, the extended Data Report designer is modified to include a Total field that calculates the value of Quantity * UnitPrice. Adding a calculated field involves the following steps:

1. Using a SQL statement in the data environment's Command object to create the calculated field.

2. Adding three text box controls to the data report: Quantity, UnitPrice, and (for the calculated field) Total.

The modified data report resembles the figure below.

Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

To add a calculated field to the data report

1. In the Data Environment designer, right-click the OrderDetails command. Then click Properties to display the OrderDetails Properties dialog box.

2. On the General tab, click the SQL Statement button, and add the following statement to the box:

Select OrderID, ProductID, UnitPrice, Quantity, (Quantity * UnitPrice) As Total From [Order Details]

The SQL statement multiplies the Quantity value by the UnitPrice value to create the Total value—the calculated field. Also note that the name of the table (Order Details) contains a space, and must be enclosed by brackets.

3. Click OK to close the dialog box.

4. From the Data Environment designer, drag the Quantity, UnitPrice, and Total fields (under the OrderDetails command) onto the Detail (Products_Detail) section of the Data Report designer.

5. Delete two Label controls, and change the Caption value of the remaining Label control to *, and arrange the controls to resemble the figure below:

http://msdn.microsoft.com/library/en-us/vbcon98/h...nAddingCalculatedFieldToDataReport.asp?frame=true (1 of 2) [11/17/2002 11:14:52 PM]


Adding a Calculated Field to the Data Report

6. On the Data Report designer, click the UnitPrice text box to select it. On the Properties window, double-click DataFormat to display the Property Pages dialog box.

7. In the Format Type box, click Currency. In the Symbol combo box, select the currency appropriate to your country.

8. Repeat steps 6 and 7 to change the DataFormat property of the Total text box to Currency.

9. Click the Total text box control to select it. On the Properties window, change the Alignment property to 1 – rptJustifyRight.

10. Save and run the project.

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Adding a Function Control to the Data Report

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/h...nAddingCalculatedFieldToDataReport.asp?frame=true (2 of 2) [11/17/2002 11:14:52 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

MSDN Library GO
Advanced Search Visual Basic Concepts

Adding a Calculated Field to the Data Report

See Also

Up One Level A calculated field is a field whose value is calculated as the report is generated. For example, when estimating the tax on an order, you must multiply the total price by the local tax rate. But
since local tax rates differ and won't be stored in the database, the tax is generated as the report is created—a calculated field.
Extending the Data Report
Adding a Calculated Field to the Data Report In this example, the extended Data Report designer is modified to include a Total field that calculates the value of Quantity * UnitPrice. Adding a calculated field involves the following
Adding a Function Control to the Data Report steps:

Grouping Information in the Data Report


Adding an Aggregate Field to the Data Report 1. Using a SQL statement in the data environment's Command object to create the calculated field.

2. Adding three text box controls to the data report: Quantity, UnitPrice, and (for the calculated field) Total.

Forcing Page Breaks in the Data Report


Adding Date, Time, Page Number, and Title to the Data Report The modified data report resembles the figure below.

Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

To add a calculated field to the data report

1. In the Data Environment designer, right-click the OrderDetails command. Then click Properties to display the OrderDetails Properties dialog box.

2. On the General tab, click the SQL Statement button, and add the following statement to the box:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAddingCalculatedFieldToDataReport.asp (1 of 2) [11/17/2002 11:14:54 PM]


Welcome to the MSDN Library

Select OrderID, ProductID, UnitPrice, Quantity, (Quantity * UnitPrice) As Total From [Order Details]

The SQL statement multiplies the Quantity value by the UnitPrice value to create the Total value—the calculated field. Also note that the name of the table (Order Details) contains a space, and must be enclosed by brackets.

3. Click OK to close the dialog box.

4. From the Data Environment designer, drag the Quantity, UnitPrice, and Total fields (under the OrderDetails command) onto the Detail (Products_Detail) section of the Data Report designer.

5. Delete two Label controls, and change the Caption value of the remaining Label control to *, and arrange the controls to resemble the figure below:

6. On the Data Report designer, click the UnitPrice text box to select it. On the Properties window, double-click DataFormat to display the Property Pages dialog box.

7. In the Format Type box, click Currency. In the Symbol combo box, select the currency appropriate to your country.

8. Repeat steps 6 and 7 to change the DataFormat property of the Total text box to Currency.

9. Click the Total text box control to select it. On the Properties window, change the Alignment property to 1 – rptJustifyRight.

10. Save and run the project.

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Adding a Function Control to the Data Report

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAddingCalculatedFieldToDataReport.asp (2 of 2) [11/17/2002 11:14:54 PM]


Adding a Function Control to the Data Report

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

Visual Basic Concepts

Adding a Function Control to the Data Report

See Also

The Data Report designer features its own set of controls. Among these, the Function control has no counterpart among the Visual Basic intrinsic controls and deserves further explanation.

The Function control displays data that is calculated at run time, using a built-in function, as the report is generated. A typical example is shown in the figure below, where the Function control is
used to display the sum of sub-totals to create a total value for a particular order.

If you have created a calculated field using a SQL statement (in the previous topic, "Adding a Calculated Field to the Data Report"), you may wonder why a Function control can't also be used to
calculate the value of Quantity * UnitPrice. In short, the Function control can calculate values only after all other records in a group section have been processed. In contrast, a SQL statement
calculates the values as part of the fields in a record as they are processed.

The steps to adding a Function control to the Data Report designer are:

1. Draw a Function control in an appropriate Footer section of the Data Report designer.

2. Set the DataMember and DataField properties to appropriate values (a numeric field from a relevant data environment Command object.)

Data Report with Function Control Showing Totals

Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

To add a Function control to the data report

1. Using the mouse pointer, click the group footer named Customers_Footer, and drag it towards the bottom of the window, to create a space between it and the Orders_Footer footer.

2. On the Toolbox, click the rptFunction control.

3. Draw the rptFunction control in the space between the two footers.

4. Set the properties of the rptFunction control according to the table below:

Property Setting

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAddingFunctionToDataReport.asp?frame=true (1 of 3) [11/17/2002 11:14:58 PM]


Adding a Function Control to the Data Report

DataMember OrderDetails

DataField Total

Name fncTotal

Alignment 1 – rptJustifyRight

DataFormat Currency

The FunctionType property of the control determines what operation will be performed with the data found in the DataField. By default, the property is set to 0-RptFuncSum, to sum the data. Other functions include: Average, Minimum, Maximum, Row Count,
STDDev (Standard Deviation), and Value Count.

5. Draw a Line control just above the Quantity text box, and a Label control to the left of the text box. Set the Caption property of the label to Total.

6. Click the fncTotal control to select it. On the Properties window, double-click Font to display the Font dialog box. Change the Font style to Bold.

7. Repeat step 6 with the Label control.

8. Position the controls on the designer to resemble the figure below:

9. Save and run the project.

Increasing the scope of the function

You can increase the scope of the function by placing the control in a lower group footer. For example, you may want to find out the grand total of each customer's set of orders.

To show a grand total for all orders

1. Draw a new Function control in the Customers_Footer section. Align the new control with the Function control created above.

2. Draw a Label control to the left of the new Function control.

3. Set the properties of the controls as shown in the table below:

Control Property Setting

rptFunction Name fncGrandTotal

rptFunction DataMember OrderDetails

rptFunction DataField Total

rptFunction Font (Font Style) Bold

rptFunction Alignment 1 – rptJustifyRight

rptLabel Caption Grand Total

rptLabel Font (Font Style) Bold

rptLabel Alignment 1 – rptJustifyRight

4. The Data Report designer should now resemble the figure below:

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAddingFunctionToDataReport.asp?frame=true (2 of 3) [11/17/2002 11:14:58 PM]


Adding a Function Control to the Data Report

5. Save and run the project.

Optional—Adding a Report Total

It's possible to increase the scope of the Function control even further. If you wish to see a total of all orders in the report, you can add a Function control to the Report Footer section.

To add a Report Total to the data report

1. Right-click the Data Report designer and click Show Report Header/Footer.

2. Add a Function control to the report footer.

3. Set the property of the control as shown in the table below:

Property Setting

Name fncReportTotal

DataMember OrderDetails

DataField Total

DataFormat Currency

Alignment 1 – rptJustifyRight

Note The number for the entire report will be especially large. Therefore the width of the Function control will have to be adjusted accordingly.

4. Save and run the project.

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Grouping Information in the Data Report

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAddingFunctionToDataReport.asp?frame=true (3 of 3) [11/17/2002 11:14:58 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

MSDN Library GO
Advanced Search Visual Basic Concepts

Adding a Function Control to the Data Report

See Also

The Data Report designer features its own set of controls. Among these, the Function control has no counterpart among the Visual Basic intrinsic controls and deserves further explanation.
Up One Level
Extending the Data Report
The Function control displays data that is calculated at run time, using a built-in function, as the report is generated. A typical example is shown in the figure below, where the Function control
Adding a Calculated Field to the Data Report is used to display the sum of sub-totals to create a total value for a particular order.

Adding a Function Control to the Data Report


Grouping Information in the Data Report If you have created a calculated field using a SQL statement (in the previous topic, "Adding a Calculated Field to the Data Report"), you may wonder why a Function control can't also be used
to calculate the value of Quantity * UnitPrice. In short, the Function control can calculate values only after all other records in a group section have been processed. In contrast, a SQL
Adding an Aggregate Field to the Data Report statement calculates the values as part of the fields in a record as they are processed.

Forcing Page Breaks in the Data Report


Adding Date, Time, Page Number, and Title to the Data Report The steps to adding a Function control to the Data Report designer are:

1. Draw a Function control in an appropriate Footer section of the Data Report designer.

2. Set the DataMember and DataField properties to appropriate values (a numeric field from a relevant data environment Command object.)

Data Report with Function Control Showing Totals

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAddingFunctionToDataReport.asp (1 of 4) [11/17/2002 11:15:29 PM]


Welcome to the MSDN Library

Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

To add a Function control to the data report

1. Using the mouse pointer, click the group footer named Customers_Footer, and drag it towards the bottom of the window, to create a space between it and the Orders_Footer footer.

2. On the Toolbox, click the rptFunction control.

3. Draw the rptFunction control in the space between the two footers.

4. Set the properties of the rptFunction control according to the table below:

Property Setting

DataMember OrderDetails

DataField Total

Name fncTotal

Alignment 1 – rptJustifyRight

DataFormat Currency

The FunctionType property of the control determines what operation will be performed with the data found in the DataField. By default, the property is set to 0-RptFuncSum, to sum the data. Other functions include: Average, Minimum, Maximum, Row
Count, STDDev (Standard Deviation), and Value Count.

5. Draw a Line control just above the Quantity text box, and a Label control to the left of the text box. Set the Caption property of the label to Total.

6. Click the fncTotal control to select it. On the Properties window, double-click Font to display the Font dialog box. Change the Font style to Bold.

7. Repeat step 6 with the Label control.

8. Position the controls on the designer to resemble the figure below:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAddingFunctionToDataReport.asp (2 of 4) [11/17/2002 11:15:29 PM]


Welcome to the MSDN Library

9. Save and run the project.

Increasing the scope of the function

You can increase the scope of the function by placing the control in a lower group footer. For example, you may want to find out the grand total of each customer's set of orders.

To show a grand total for all orders

1. Draw a new Function control in the Customers_Footer section. Align the new control with the Function control created above.

2. Draw a Label control to the left of the new Function control.

3. Set the properties of the controls as shown in the table below:

Control Property Setting

rptFunction Name fncGrandTotal

rptFunction DataMember OrderDetails

rptFunction DataField Total

rptFunction Font (Font Style) Bold

rptFunction Alignment 1 – rptJustifyRight

rptLabel Caption Grand Total

rptLabel Font (Font Style) Bold

rptLabel Alignment 1 – rptJustifyRight

4. The Data Report designer should now resemble the figure below:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAddingFunctionToDataReport.asp (3 of 4) [11/17/2002 11:15:29 PM]


Welcome to the MSDN Library

5. Save and run the project.

Optional—Adding a Report Total

It's possible to increase the scope of the Function control even further. If you wish to see a total of all orders in the report, you can add a Function control to the Report Footer section.

To add a Report Total to the data report

1. Right-click the Data Report designer and click Show Report Header/Footer.

2. Add a Function control to the report footer.

3. Set the property of the control as shown in the table below:

Property Setting

Name fncReportTotal

DataMember OrderDetails

DataField Total

DataFormat Currency

Alignment 1 – rptJustifyRight

Note The number for the entire report will be especially large. Therefore the width of the Function control will have to be adjusted accordingly.

4. Save and run the project.

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Grouping Information in the Data Report

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAddingFunctionToDataReport.asp (4 of 4) [11/17/2002 11:15:29 PM]


Grouping Information in the Data Report

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

Visual Basic Concepts

Grouping Information in the Data Report

See Also

Information that is grouped can give the user a different perspective on data. Working in tandem with the Data Environment designer, the Data Report designer gives you the ability to group data
according to any field in a table. The figure below shows a data report grouped by countries.

Data Report Grouped By Country

Grouping by Command Field


The grouping field provided by the data environment's Command object differs from the grouping already achieved by creating group headers and footers. Instead of using the table of a database
as the basis for grouping, the Grouping feature of the Data Environment designer allows you to select a particular field in the table as the grouping field without having to create a new Command
object.

The steps to adding a grouping field include:

1. Creating a group field in the Data Environment designer.

2. Adding a Group Header/Footer to the Data Report designer to correspond to the new command.

3. Resetting the DataMember property of the data report to the new Grouping Command object created in the data environment.

4. Dragging the group field from the data environment to the data report.

Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

To add a grouping field to the Data Report designer

1. In the Data Environment designer, right click the Customers Command object. Click Properties to show the Customers Properties dialog box.

2. Click the Grouping tab.

http://msdn.microsoft.com/library/en-us/vbcon98/h...conGroupingInformationInDataReport.asp?frame=true (1 of 2) [11/17/2002 11:15:38 PM]


Grouping Information in the Data Report
3. Click Group Command Object.

4. In the Fields in Command box, double-click Country. Click OK to close the dialog box.

Notice that the Customers Command object has been renamed as Customers Grouped using Customers_Grouping, and that two new folders have been created for the fields. The first, Summary fields in Customer_Grouping contains the field(s) that the
subordinate fields will be grouped by. The subordinate fields are contained in the second folder, Detail Fields in Customer_Grouping.

5. Right-click the Data Report designer, and then click Insert Group Header/Footer.

6. Click the up arrow three times to insert the group header at the outermost edge of the header/footer pairs. Click OK to close the dialog box.

7. On the Data Report designer, click the new Group Header to select it, and change its name from Section1 to Customers_Grouping_Header in the Properties window. Click the new Group Footer to select it, and change its name to
Customers_Grouping_Footer.

8. Click the Data Report designer's title bar to select the entire data report. On the Properties window, click DataMember and change the property from Customers to Customers_Grouping.

When the grouping field was added to the data environment, the equivalent of a new Command object was also added to the data report. That virtual Command object is displayed in the drop-down list of data members as Customers_Grouping.

9. In the Data Environment designer, open Summary Fields in Customers_Grouping. Drag the Country field into the new section on the Data Report designer.

10. Delete the Label control that accompanies the Country field. Place the new field at the leftmost edge of the designer, which should now resemble the figure below:

11. Save and run the project.

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Adding an Aggregate Field to the Data Report

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/h...conGroupingInformationInDataReport.asp?frame=true (2 of 2) [11/17/2002 11:15:38 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

MSDN Library GO
Advanced Search Visual Basic Concepts

Grouping Information in the Data Report

See Also

Up One Level Information that is grouped can give the user a different perspective on data. Working in tandem with the Data Environment designer, the Data Report designer gives you the ability to group
data according to any field in a table. The figure below shows a data report grouped by countries.
Extending the Data Report
Adding a Calculated Field to the Data Report Data Report Grouped By Country
Adding a Function Control to the Data Report
Grouping Information in the Data Report
Adding an Aggregate Field to the Data Report
Forcing Page Breaks in the Data Report
Adding Date, Time, Page Number, and Title to the Data Report

Grouping by Command Field


The grouping field provided by the data environment's Command object differs from the grouping already achieved by creating group headers and footers. Instead of using the table of a
database as the basis for grouping, the Grouping feature of the Data Environment designer allows you to select a particular field in the table as the grouping field without having to create a
new Command object.

The steps to adding a grouping field include:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconGroupingInformationInDataReport.asp (1 of 3) [11/17/2002 11:15:40 PM]


Welcome to the MSDN Library

1. Creating a group field in the Data Environment designer.

2. Adding a Group Header/Footer to the Data Report designer to correspond to the new command.

3. Resetting the DataMember property of the data report to the new Grouping Command object created in the data environment.

4. Dragging the group field from the data environment to the data report.

Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

To add a grouping field to the Data Report designer

1. In the Data Environment designer, right click the Customers Command object. Click Properties to show the Customers Properties dialog box.

2. Click the Grouping tab.

3. Click Group Command Object.

4. In the Fields in Command box, double-click Country. Click OK to close the dialog box.

Notice that the Customers Command object has been renamed as Customers Grouped using Customers_Grouping, and that two new folders have been created for the fields. The first, Summary fields in Customer_Grouping contains the field(s) that
the subordinate fields will be grouped by. The subordinate fields are contained in the second folder, Detail Fields in Customer_Grouping.

5. Right-click the Data Report designer, and then click Insert Group Header/Footer.

6. Click the up arrow three times to insert the group header at the outermost edge of the header/footer pairs. Click OK to close the dialog box.

7. On the Data Report designer, click the new Group Header to select it, and change its name from Section1 to Customers_Grouping_Header in the Properties window. Click the new Group Footer to select it, and change its name to
Customers_Grouping_Footer.

8. Click the Data Report designer's title bar to select the entire data report. On the Properties window, click DataMember and change the property from Customers to Customers_Grouping.

When the grouping field was added to the data environment, the equivalent of a new Command object was also added to the data report. That virtual Command object is displayed in the drop-down list of data members as Customers_Grouping.

9. In the Data Environment designer, open Summary Fields in Customers_Grouping. Drag the Country field into the new section on the Data Report designer.

10. Delete the Label control that accompanies the Country field. Place the new field at the leftmost edge of the designer, which should now resemble the figure below:

11. Save and run the project.

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Adding an Aggregate Field to the Data Report

Start from the beginning Creating a Simple Data Report

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconGroupingInformationInDataReport.asp (2 of 3) [11/17/2002 11:15:40 PM]


Welcome to the MSDN Library

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconGroupingInformationInDataReport.asp (3 of 3) [11/17/2002 11:15:40 PM]


Adding an Aggregate Field to the Data Report

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

Visual Basic Concepts

Adding an Aggregate Field to the Data Report

See Also

In the Data Environment designer you can also create aggregate fields—fields that summarize data from a section. An aggregate field is thus similar to the Function control in that both are
calculated as the report is generated. But there are a few differences: whereas the Function control can only be placed in a Group Footer, an aggregate field can be placed in any section of the
Data Report designer, except the Report Header/Footer and Page Header/Footer sections.

Another difference is found in how the two fields are created: while the Function control is a feature of the Data Report designer, the aggregate field is a feature of the Data Environment designer.
The steps to adding an aggregate field to the report are:

1. Create an aggregate field in the Data Environment designer.

2. From the Data Environment designer, drag the aggregate field onto the Data Report designer.

As an example, the figure below shows an aggregate field that displays the number of products ordered.

Data Report with Aggregate Field

Using a Function control can be more efficient than an aggregate field. When the data report calculates the value for a Function control, it takes a certain amount of processing to create each
value. When the data environment creates an aggregate field, it takes a similar amount of processing. However, you can save that processing time by using the Function control because the Data
Report designer must create the entire report in its own process.

Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

To create an aggregate field in the data environment

1. On the Data Environment designer, open the Detail Fields in Customers folder, and right-click Orders, then click Properties.

2. On the Orders Properties dialog box, click the Aggregates tab.

3. Click the Add button.

4. Click the Name box and type ProductCount.

5. In the Function combo box, select CNT.

6. In the Aggregate combo box, select OrderDetails (it should be selected by default).

7. In the Field combo box, select ProductID.

8. Click OK to close the dialog box.

Now that you have created the aggregate field, you can place it on the Data Report designer.

To Add the aggregate field to the data report

1. From the Data Environment designer, drag the ProductCount aggregate field onto the group section named Orders_Header.

2. Change the Caption of the Label control to Product(s) Ordered.

3. Reposition and resize the TextBox control and the Label control so the designer resembles the figure below:

4. Save and run the project.

http://msdn.microsoft.com/library/en-us/vbcon98/...nAddingAggregateFieldToDataReport.asp?frame=true (1 of 2) [11/17/2002 11:15:47 PM]


Adding an Aggregate Field to the Data Report

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Forcing Page Breaks in the Data Report

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/...nAddingAggregateFieldToDataReport.asp?frame=true (2 of 2) [11/17/2002 11:15:47 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

MSDN Library GO
Advanced Search Visual Basic Concepts

Adding an Aggregate Field to the Data Report

See Also

Up One Level In the Data Environment designer you can also create aggregate fields—fields that summarize data from a section. An aggregate field is thus similar to the Function control in that both are
calculated as the report is generated. But there are a few differences: whereas the Function control can only be placed in a Group Footer, an aggregate field can be placed in any section of the
Extending the Data Report Data Report designer, except the Report Header/Footer and Page Header/Footer sections.

Adding a Calculated Field to the Data Report


Adding a Function Control to the Data Report Another difference is found in how the two fields are created: while the Function control is a feature of the Data Report designer, the aggregate field is a feature of the Data Environment
designer. The steps to adding an aggregate field to the report are:
Grouping Information in the Data Report
Adding an Aggregate Field to the Data Report 1. Create an aggregate field in the Data Environment designer.

Forcing Page Breaks in the Data Report 2. From the Data Environment designer, drag the aggregate field onto the Data Report designer.

Adding Date, Time, Page Number, and Title to the Data Report
As an example, the figure below shows an aggregate field that displays the number of products ordered.

Data Report with Aggregate Field

Using a Function control can be more efficient than an aggregate field. When the data report calculates the value for a Function control, it takes a certain amount of processing to create each
value. When the data environment creates an aggregate field, it takes a similar amount of processing. However, you can save that processing time by using the Function control because the
Data Report designer must create the entire report in its own process.

Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

To create an aggregate field in the data environment

1. On the Data Environment designer, open the Detail Fields in Customers folder, and right-click Orders, then click Properties.

2. On the Orders Properties dialog box, click the Aggregates tab.

3. Click the Add button.

4. Click the Name box and type ProductCount.

5. In the Function combo box, select CNT.

6. In the Aggregate combo box, select OrderDetails (it should be selected by default).

7. In the Field combo box, select ProductID.

8. Click OK to close the dialog box.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAddingAggregateFieldToDataReport.asp (1 of 2) [11/17/2002 11:15:49 PM]


Welcome to the MSDN Library
Now that you have created the aggregate field, you can place it on the Data Report designer.

To Add the aggregate field to the data report

1. From the Data Environment designer, drag the ProductCount aggregate field onto the group section named Orders_Header.

2. Change the Caption of the Label control to Product(s) Ordered.

3. Reposition and resize the TextBox control and the Label control so the designer resembles the figure below:

4. Save and run the project.

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Forcing Page Breaks in the Data Report

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAddingAggregateFieldToDataReport.asp (2 of 2) [11/17/2002 11:15:49 PM]


Forcing Page Breaks in the Data Report

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

Visual Basic Concepts

Forcing Page Breaks in the Data Report

See Also

A page break helps to make a report more readable (and therefore understandable) by breaking the data into logical chunks of information. The Data Report designer allows you to force page
breaks before or after any group header or footer, or force a page break after the report header or before the report footer. (Forcing of page breaks on page headers and page footers is ignored
because they already occur before and after a page break.)

Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

The example below adds a page break before the group header that contains the CompanyName field.

To force a page break before the CompanyName field

1. Click the group header named Customers to select it.

2. On the Properties window, click ForcePageBreak, then click the arrow that appears at the right of the box.

3. Click the 1 – rptPageBreakBefore from the drop-down list.

4. Run the project.

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Adding Date, Time, Page Number, and Title to the Data Report

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconForcingPageBreaksInDataReport.asp?frame=true [11/17/2002 11:15:54 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

MSDN Library GO
Advanced Search Visual Basic Concepts

Forcing Page Breaks in the Data Report

See Also

Up One Level A page break helps to make a report more readable (and therefore understandable) by breaking the data into logical chunks of information. The Data Report designer allows you to force page
breaks before or after any group header or footer, or force a page break after the report header or before the report footer. (Forcing of page breaks on page headers and page footers is
Extending the Data Report ignored because they already occur before and after a page break.)

Adding a Calculated Field to the Data Report


Adding a Function Control to the Data Report Note This topic is part of a series that walks you through creating a sample data report. It begins with the topic, Creating a Simple Data Report.

Grouping Information in the Data Report


Adding an Aggregate Field to the Data Report The example below adds a page break before the group header that contains the CompanyName field.

Forcing Page Breaks in the Data Report


Adding Date, Time, Page Number, and Title to the Data Report To force a page break before the CompanyName field

1. Click the group header named Customers to select it.

2. On the Properties window, click ForcePageBreak, then click the arrow that appears at the right of the box.

3. Click the 1 – rptPageBreakBefore from the drop-down list.

4. Run the project.

Step by Step

This topic is part of a series that walks you through creating a sample data report.

To See

Go to the next step Adding Date, Time, Page Number, and Title to the Data Report

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconForcingPageBreaksInDataReport.asp [11/17/2002 11:15:56 PM]


Adding Date, Time, Page Number, and Title to the Data Report

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

Visual Basic Concepts

Adding Date, Time, Page Number, and Title to the Data Report

See Also

You can add Header and Footer data to each page of a data report by adding an appropriate Label control to the Page Header or Page Footer section. The Data Report designer features the
following header and footer sections:

● Report Header—Occurs only once, at the very top of the report. Can be used for introductory material, such as the purpose of the report.

● Report Footer—Like the Report Header, occurs only once, at the very end of the report. Can be used for summary material, such as conclusions, or highlights of the report, or grand totals using the Function control.

● Page Header—Occurs at the top of every page. Can be used for page number, date and time of the report, or title of the report.

● Page Footer—Occurs at the bottom of every page. Can also be used for page number, date and time of the report, or other incidental information.

The Data Report designer contains several pre-configured controls that can be used to quickly add the date, time, page number, or report title to any section of the report. These controls are
simply Label controls containing codes that display the following information:

Function Code

Current Page Number %p

Total Number of Pages %P

Current Date (Short Format) %d

Current Date (Long Format) %D

Current Time (Short Format) %t

Current Time (Long Format) %T

Report Title %i

Note To display a percent sign, use %%.

To add the title and page numbers to the page header

1. Click the Data Report designer's title bar to select it.

2. On the Properties window, click Title and type Orders By Date Under Customer Grouped by Country. This is the title that will display in the page header.

3. Right-click the Data Report designer and click Show Page Header/Footer.

4. Right-click the page header section and click Insert Control.

5. From the menu, click Report Title.

6. Reposition the new control in the middle of the section, extending it wide enough to display the entire report title.

7. Repeat step 4.

8. From the menu, click Current Page Number.

9. Position the new control in the far right corner of the designer.

10. Set the new control's Alignment property to 1 – Justify Right.

Step by Step

This topic is the last in a series that walks you through creating a sample data report.

To See

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAddingHeaderFootersToDataReport.asp?frame=true [11/17/2002 11:16:02 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer > Creating a Simple Data Report

MSDN Library GO
Advanced Search Visual Basic Concepts

Adding Date, Time, Page Number, and Title to the Data Report

See Also

Up One Level You can add Header and Footer data to each page of a data report by adding an appropriate Label control to the Page Header or Page Footer section. The Data Report designer features the
following header and footer sections:
Extending the Data Report
Adding a Calculated Field to the Data Report ● Report Header—Occurs only once, at the very top of the report. Can be used for introductory material, such as the purpose of the report.

Adding a Function Control to the Data Report ● Report Footer—Like the Report Header, occurs only once, at the very end of the report. Can be used for summary material, such as conclusions, or highlights of the report, or grand totals using the Function control.

● Page Header—Occurs at the top of every page. Can be used for page number, date and time of the report, or title of the report.

Grouping Information in the Data Report ● Page Footer—Occurs at the bottom of every page. Can also be used for page number, date and time of the report, or other incidental information.

Adding an Aggregate Field to the Data Report


The Data Report designer contains several pre-configured controls that can be used to quickly add the date, time, page number, or report title to any section of the report. These controls are
Forcing Page Breaks in the Data Report simply Label controls containing codes that display the following information:

Adding Date, Time, Page Number, and Title to the Data Report

Function Code

Current Page Number %p

Total Number of Pages %P

Current Date (Short Format) %d

Current Date (Long Format) %D

Current Time (Short Format) %t

Current Time (Long Format) %T

Report Title %i

Note To display a percent sign, use %%.

To add the title and page numbers to the page header

1. Click the Data Report designer's title bar to select it.

2. On the Properties window, click Title and type Orders By Date Under Customer Grouped by Country. This is the title that will display in the page header.

3. Right-click the Data Report designer and click Show Page Header/Footer.

4. Right-click the page header section and click Insert Control.

5. From the menu, click Report Title.

6. Reposition the new control in the middle of the section, extending it wide enough to display the entire report title.

7. Repeat step 4.

8. From the menu, click Current Page Number.

9. Position the new control in the far right corner of the designer.

10. Set the new control's Alignment property to 1 – Justify Right.

Step by Step

This topic is the last in a series that walks you through creating a sample data report.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAddingHeaderFootersToDataReport.asp (1 of 2) [11/17/2002 11:16:05 PM]


Welcome to the MSDN Library
To See

Start from the beginning Creating a Simple Data Report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAddingHeaderFootersToDataReport.asp (2 of 2) [11/17/2002 11:16:05 PM]


Exporting a Data Report

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer

Visual Basic Concepts

Exporting a Data Report

See Also

After compiling a report you may wish to reuse it, either as part of a larger document or perhaps for distribution on an intranet or the Internet. The Data Report designer's ExportReport method
allows you to accomplish these tasks. Using the ExportReport method, you can export any report as a text file or as an HTML file. Additionally, you can use any of a number of ExportFormat
objects to tailor the content and appearance of an exported file.

Important The ExportReport method does not support the exporting of images or graphic shapes.

ExportFormat Objects

The ExportReport method was designed to work with the ExportFormats collection. Each ExportFormat object in the collection represents a separate format for the report. For example, a report
formatted for intranet distribution might include names of groups or employees as part of the report header; for Internet distribution, those same names would be removed or replaced. You would
therefore create at least two ExportFormat objects, each tailored for the distribution mechanism. However, it is possible to export a report without creating any ExportFormat objects because four
are already provided for you.

Four Default ExportFormat Objects

By default, the ExportFormats collection contains four members. The four members and their associated file filters are shown in the chart below:

Object File Filter Description

ExportFormats(1) *.htm, *.html HTML

ExportFormats(2) *.htm, *.html Unicode HTML

ExportFormats(3) *.txt Text

ExportFormats(4) *.txt Unicode Text

If you need to use any of the default types, you can also use the Key property to specify a default type. The Key property values and the constants are shown below:

Object Key Constant

ExportFormats(1) key_def_HTML rptKeyHTML

ExportFormats(2) key_def_UnicodeHTML_UTF8 rptKeyUnicodeHTML_UTF8

ExportFormats(3) key_def_Text rptKeyText

ExportFormats(4) key_def_UnicodeText rptKeyUnicodeText

By using one of the four members, you can export a report without creating another ExportFormat object, provided the default meets your requirements. For example, to export a daily HTML
report, you might use the following code:

DataReport1.ExportReport rptKeyHTML

Displaying a Dialog Box Is Optional


The programmer can determine whether or not a dialog box will be presented when exporting a report. For example, if the report is created automatically every morning, and written to the same
file for distribution by an intranet, there is no need to display a dialog box. As long as a valid file path and key are supplied, and the Overwrite parameter is set to True, the dialog will not be
displayed.

' Export a report as HTML, overwriting any existing file. Export


' all pages to the Daily_Report.htm file.
DataReport1.ExportReport rptKeyHTML, "C:\Temp\Daily_Report", True, , _
rptRangeAllPages

Note In the above code the second argument seems to be a directory but is actually the file name. "Daily_Report.htm" is the name of the written file. The ExportFormat object supplies the file

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconExportingDataReport.asp?frame=true (1 of 3) [11/17/2002 11:16:17 PM]


Exporting a Data Report

extension (.htm), and thus there's no need to write it in the file name argument.

ExportFormat Supplies Dialog Information


The ExportFormat object also contains the information that is displayed when the user invokes the ExportReport method. In particular, the FileFormatString property sets the text that is displayed
in the Export dialog box's Save As Type box. For example, imagine that a company has a standard ExportFormat object to be used with all reports. The following code would ensure that the
ExportFormat is available from the list of format types on the Export dialog box:

Dim strTemplate As String

' First create the template for the ExportFormat object.


strTemplate = "MyCompany Daily Report" & vbCrLf & rptTagBody

' Add an ExportFormat object. The FileFormatString determines


' what will be displayed in the Export dialog box.
DataReport1.ExportFormats.Add _
Key:="StandardReport", _
FormatType:=rptFmtText, _
FileFormatString:="Standard Report (*.txt)", _
FileFilter:="*.txt", _
Template:=strTemplate

' Invoke the ExportReport method specifying the ExportFormat


' object named StandardReport to use.
DataReport1.ExportReport "StandardReport", , False, True, _
rptRangeFromTo, 1, 10

When invoked, the Export dialog box resembles this:

Template Codes
The core of an ExportFormat object is its template. A template is simply a string containing both the text you want to appear along with constants that represent various parts of the data report.
The constants, values, and descriptions are shown in the table below:

Constant Value Description

rptTagTitle <!--MSDBRPT_Template_Title--> Represents the title of the report, as found in the Title property.

rptTagBody <!--MSDBRPT_Template_Body--> Represents the body of the report.

To create a simple data report that includes only the name of the author followed by the body of the report, the template would resemble this:

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconExportingDataReport.asp?frame=true (2 of 3) [11/17/2002 11:16:17 PM]


Exporting a Data Report

Dim strT As String


strT = "Author: " & InputBox("Your name") & vbCrLf & rptTagBody
drpNwind.ExportFormats.Add "AuExp", rptFmtText, _
"Author Only Text File", "*.txt", strT

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconExportingDataReport.asp?frame=true (3 of 3) [11/17/2002 11:16:17 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Exporting a Data Report

See Also

Up One Level After compiling a report you may wish to reuse it, either as part of a larger document or perhaps for distribution on an intranet or the Internet. The Data Report designer's ExportReport
method allows you to accomplish these tasks. Using the ExportReport method, you can export any report as a text file or as an HTML file. Additionally, you can use any of a number of
Parts of the Data Report ExportFormat objects to tailor the content and appearance of an exported file.

Creating a Simple Data Report


Exporting a Data Report Important The ExportReport method does not support the exporting of images or graphic shapes.

Printing the Data Report


Data Report Events ExportFormat Objects

Understanding Control Placement on the Data Report Designer


The ExportReport method was designed to work with the ExportFormats collection. Each ExportFormat object in the collection represents a separate format for the report. For example, a
report formatted for intranet distribution might include names of groups or employees as part of the report header; for Internet distribution, those same names would be removed or replaced.
You would therefore create at least two ExportFormat objects, each tailored for the distribution mechanism. However, it is possible to export a report without creating any ExportFormat
objects because four are already provided for you.

Four Default ExportFormat Objects

By default, the ExportFormats collection contains four members. The four members and their associated file filters are shown in the chart below:

Object File Filter Description

ExportFormats(1) *.htm, *.html HTML

ExportFormats(2) *.htm, *.html Unicode HTML

ExportFormats(3) *.txt Text

ExportFormats(4) *.txt Unicode Text

If you need to use any of the default types, you can also use the Key property to specify a default type. The Key property values and the constants are shown below:

Object Key Constant

ExportFormats(1) key_def_HTML rptKeyHTML

ExportFormats(2) key_def_UnicodeHTML_UTF8 rptKeyUnicodeHTML_UTF8

ExportFormats(3) key_def_Text rptKeyText

ExportFormats(4) key_def_UnicodeText rptKeyUnicodeText

By using one of the four members, you can export a report without creating another ExportFormat object, provided the default meets your requirements. For example, to export a daily HTML
report, you might use the following code:

DataReport1.ExportReport rptKeyHTML

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconExportingDataReport.asp (1 of 3) [11/17/2002 11:16:18 PM]


Welcome to the MSDN Library

Displaying a Dialog Box Is Optional


The programmer can determine whether or not a dialog box will be presented when exporting a report. For example, if the report is created automatically every morning, and written to the
same file for distribution by an intranet, there is no need to display a dialog box. As long as a valid file path and key are supplied, and the Overwrite parameter is set to True, the dialog will
not be displayed.

' Export a report as HTML, overwriting any existing file. Export


' all pages to the Daily_Report.htm file.
DataReport1.ExportReport rptKeyHTML, "C:\Temp\Daily_Report", True, , _
rptRangeAllPages

Note In the above code the second argument seems to be a directory but is actually the file name. "Daily_Report.htm" is the name of the written file. The ExportFormat object supplies the
file extension (.htm), and thus there's no need to write it in the file name argument.

ExportFormat Supplies Dialog Information


The ExportFormat object also contains the information that is displayed when the user invokes the ExportReport method. In particular, the FileFormatString property sets the text that is
displayed in the Export dialog box's Save As Type box. For example, imagine that a company has a standard ExportFormat object to be used with all reports. The following code would ensure
that the ExportFormat is available from the list of format types on the Export dialog box:

Dim strTemplate As String

' First create the template for the ExportFormat object.


strTemplate = "MyCompany Daily Report" & vbCrLf & rptTagBody

' Add an ExportFormat object. The FileFormatString determines


' what will be displayed in the Export dialog box.
DataReport1.ExportFormats.Add _
Key:="StandardReport", _
FormatType:=rptFmtText, _
FileFormatString:="Standard Report (*.txt)", _
FileFilter:="*.txt", _
Template:=strTemplate

' Invoke the ExportReport method specifying the ExportFormat


' object named StandardReport to use.
DataReport1.ExportReport "StandardReport", , False, True, _
rptRangeFromTo, 1, 10

When invoked, the Export dialog box resembles this:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconExportingDataReport.asp (2 of 3) [11/17/2002 11:16:18 PM]


Welcome to the MSDN Library
Template Codes
The core of an ExportFormat object is its template. A template is simply a string containing both the text you want to appear along with constants that represent various parts of the data
report. The constants, values, and descriptions are shown in the table below:

Constant Value Description

rptTagTitle <!--MSDBRPT_Template_Title--> Represents the title of the report, as found in the Title property.

rptTagBody <!--MSDBRPT_Template_Body--> Represents the body of the report.

To create a simple data report that includes only the name of the author followed by the body of the report, the template would resemble this:

Dim strT As String


strT = "Author: " & InputBox("Your name") & vbCrLf & rptTagBody
drpNwind.ExportFormats.Add "AuExp", rptFmtText, _
"Author Only Text File", "*.txt", strT

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconExportingDataReport.asp (3 of 3) [11/17/2002 11:16:18 PM]


Printing a Data Report

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer

Visual Basic Concepts

Printing a Data Report

See Also

Printing a data report can be accomplished in one of two ways. The user can click the Print button that appears on the data report in Print Preview mode (using the Show method), or you can
programmatically enable printing using the PrintReport method. If an error occurs during printing, trap it in the Error event.

For More Information See "Data Report Events."

Choosing to Display a Print Dialog Box

When printing a report programmatically, you have two choices: to print by displaying the Print dialog box, or by printing without displaying the dialog box.

To display the Print dialog box

1. Add a CommandButton to a Form.

2. In the button's Click event, place the following code:

DataReport1.PrintReport True

The Print dialog box allows the user to select a printer, print to file, select a range of pages to print, and specify the number of copies to print.

Note Printers must be installed on the computer in order to present a choice of printers.

Printing Without a Dialog Box

In some cases, you may wish to print the report without user intervention. The PrintReport method also gives you the option of selecting a range of pages to print, either all, or a specified range.

To print without displaying the dialog box

1. Add a CommandButton to a Form.

2. In the button's Click event, place the following code:

DataReport1.PrintReport False

Or, to specify a range of pages to print, use the code below:

DataReport1.PrintReport False, rptRangeFromTo, 1, 2

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconPrintingWithDataReport.asp?frame=true [11/17/2002 11:16:24 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Printing a Data Report

See Also

Up One Level Printing a data report can be accomplished in one of two ways. The user can click the Print button that appears on the data report in Print Preview mode (using the Show method), or you can
programmatically enable printing using the PrintReport method. If an error occurs during printing, trap it in the Error event.
Parts of the Data Report
Creating a Simple Data Report For More Information See "Data Report Events."
Exporting a Data Report
Printing the Data Report Choosing to Display a Print Dialog Box
Data Report Events
Understanding Control Placement on the Data Report Designer When printing a report programmatically, you have two choices: to print by displaying the Print dialog box, or by printing without displaying the dialog box.

To display the Print dialog box

1. Add a CommandButton to a Form.

2. In the button's Click event, place the following code:

DataReport1.PrintReport True

The Print dialog box allows the user to select a printer, print to file, select a range of pages to print, and specify the number of copies to print.

Note Printers must be installed on the computer in order to present a choice of printers.

Printing Without a Dialog Box

In some cases, you may wish to print the report without user intervention. The PrintReport method also gives you the option of selecting a range of pages to print, either all, or a specified
range.

To print without displaying the dialog box

1. Add a CommandButton to a Form.

2. In the button's Click event, place the following code:

DataReport1.PrintReport False

Or, to specify a range of pages to print, use the code below:

DataReport1.PrintReport False, rptRangeFromTo, 1, 2

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconPrintingWithDataReport.asp [11/17/2002 11:16:26 PM]


Data Report Events

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer

Visual Basic Concepts

Data Report Events

See Also

Like the standard Visual Basic form, the life of a Data Report designer is marked by certain key events. Those events, and the order in which they occur, are shown in the following table:

Event Description

Initialize Occurs after the query has completed, and controls are sited on the form.

Resize Occurs when the designer is first displayed or when the window state of an object changes.

Activate Occurs when the designer becomes the active window.

ProcessingTimeout Occurs approximately once every second until all processing has ended. Use this event to determine if processing has taken too long, and to cancel the processing.

Note This event will not occur until the query has completed. See below.

[Deactivate] Occurs when the designer is no longer the active window. Use this event to determine if the user has clicked another form or designer.

QueryClose Occurs before the designer is terminated. Set the Cancel argument to True to cancel termination. The CloseMode argument returns the type of action that is causing the termination.

Terminate Occurs when all references to the designer have been set to 0.

Timeout and Asynchronous Call Events

In addition to the designer's lifetime events, the DataReport object also features events that allow you to trap errors and monitor synchronous and asynchronous function calls.

ExportReport and PrintReport: Query, Synchronous and


Asynchronous Processes
When either the ExportReport or PrintReport method is invoked, the process is divided into three stages—the query, synchronous processing, and asynchronous printing or exportation:

1. Query—When the data report is first created, a query is sent to the data provider.

2. Processing—The data retrieved by the query is processed by Visual Basic to create the report. The data is cached in a temporary file on the computer. This process is synchronous.

3. Asynchronous Printing or Exporting—After creating the report, the report is exported or printed. This process is asynchronous.

When the Show method is invoked, the data report executes the query and then processes the data in a synchronous process before displaying the report.

Because these methods combine both synchronous and asynchronous processes, there are separate events to monitor each kind of process.

The ProcessTimeOut Event—for Synchronous Functions


Processing a large data report may take some time. If you want to allow your users to cancel out of a lengthy operation (such as Show, ExportReport, or PrintReport), you can use the
ProcessingTimeout event to monitor how many seconds have passed, and set the cancel argument to True at the user's command. The code below shows an example.

Private Sub DataReport_ProcessingTimeout(ByVal Seconds As Long, _


Cancel As Boolean, ByVal JobType As MSDataReportLib.AsyncTypeConstants, _
ByVal Cookie As Long)
Select Case Seconds
Case 30
If MsgBox("This has taken " & Seconds & "seconds. Cancel?", _
vbRetryCancel) = vbCancel Then
Cancel = True
End If
Case 45
If MsgBox("This has taken " & Seconds & "seconds. Cancel?", _
vbRetryCancel) = vbCancel Then
Cancel = True
End If
Case 60
'Cancel automatically after 60 seconds.
Cancel = True

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconHandlingDataReportErrors.asp?frame=true (1 of 2) [11/17/2002 11:16:32 PM]


Data Report Events
End Select
End Sub

Note It is not guaranteed that the ProcessingTimeout event will occur at the intervals specified above. For example, other Visual Basic code running in the background may prevent the event
from occurring. In that case, set the Case statement to a range of values; when the event occurs, set a module-level flag to True, and check it on subsequent occurrences.

Error Event—For Asynchronous Functions


To trap errors that occur when no Visual Basic code is executing (that is, an asynchronous function), use the Error event. For example, if the PrintReport or ExportReport method fails in the
asynchronous stage, the Error event will occur. The example below traps asynchronous errors:

Private Sub DataReport_Error(ByVal JobType As _


MSDataReportLib.AsyncTypeConstants, ByVal Cookie As Long, _
ByVal ErrObj As MSDataReportLib.RptError, ShowError As Boolean)
Select Case JobType ' The JobType identifies the process.
Case rptAsyncPrint
' Trap PrintReport errors here.
Case rptAsyncReport
' Trap ExportReport errors here.
End Select
End Sub

You can also use the Error event to trap specific cases, such as the lack of a printer on the computer, as shown in the code below:

Private Sub DataReport_Error(ByVal JobType As _


MSDataReportLib.AsyncTypeConstants, ByVal Cookie As Long, _
ByVal ErrObj As MSDataReportLib.RptError, ShowError As Boolean)
Select Case ErrObj.ErrorNumber
Case rptErrPrinterInfo ' 8555
MsgBox "A printing error has occurred. " & _
"You may not have a Printer installed."
ShowError = False
Exit Sub
Case Else
' handle other cases here.
ShowError = True
End Select
End Sub

The AsyncProgress Event


The AsyncProgress event is not designed to trap errors, but to allow you to monitor the state of the asynchronous function. By the time this event occurs, all of the data has been processed; thus
two of the event's arguments are PagesCompleted and TotalPages. The event also includes arguments that identify the asynchronous operation: the JobType and Cookie arguments can then be
used to monitor the progress of any process.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconHandlingDataReportErrors.asp?frame=true (2 of 2) [11/17/2002 11:16:32 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Data Report Events

See Also

Up One Level Like the standard Visual Basic form, the life of a Data Report designer is marked by certain key events. Those events, and the order in which they occur, are shown in the following table:

Parts of the Data Report


Creating a Simple Data Report Event Description

Exporting a Data Report


Initialize Occurs after the query has completed, and controls are sited on the form.

Printing the Data Report


Data Report Events
Resize Occurs when the designer is first displayed or when the window state of an object changes.

Understanding Control Placement on the Data Report Designer Activate Occurs when the designer becomes the active window.

ProcessingTimeout Occurs approximately once every second until all processing has ended. Use this event to determine if processing has taken too long, and to cancel the processing.

Note This event will not occur until the query has completed. See below.

[Deactivate] Occurs when the designer is no longer the active window. Use this event to determine if the user has clicked another form or designer.

QueryClose Occurs before the designer is terminated. Set the Cancel argument to True to cancel termination. The CloseMode argument returns the type of action that is causing the termination.

Terminate Occurs when all references to the designer have been set to 0.

Timeout and Asynchronous Call Events

In addition to the designer's lifetime events, the DataReport object also features events that allow you to trap errors and monitor synchronous and asynchronous function calls.

ExportReport and PrintReport: Query, Synchronous and


Asynchronous Processes
When either the ExportReport or PrintReport method is invoked, the process is divided into three stages—the query, synchronous processing, and asynchronous printing or exportation:

1. Query—When the data report is first created, a query is sent to the data provider.

2. Processing—The data retrieved by the query is processed by Visual Basic to create the report. The data is cached in a temporary file on the computer. This process is synchronous.

3. Asynchronous Printing or Exporting—After creating the report, the report is exported or printed. This process is asynchronous.

When the Show method is invoked, the data report executes the query and then processes the data in a synchronous process before displaying the report.

Because these methods combine both synchronous and asynchronous processes, there are separate events to monitor each kind of process.

The ProcessTimeOut Event—for Synchronous Functions


Processing a large data report may take some time. If you want to allow your users to cancel out of a lengthy operation (such as Show, ExportReport, or PrintReport), you can use the
ProcessingTimeout event to monitor how many seconds have passed, and set the cancel argument to True at the user's command. The code below shows an example.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconHandlingDataReportErrors.asp (1 of 2) [11/17/2002 11:16:36 PM]


Welcome to the MSDN Library

Private Sub DataReport_ProcessingTimeout(ByVal Seconds As Long, _


Cancel As Boolean, ByVal JobType As MSDataReportLib.AsyncTypeConstants, _
ByVal Cookie As Long)
Select Case Seconds
Case 30
If MsgBox("This has taken " & Seconds & "seconds. Cancel?", _
vbRetryCancel) = vbCancel Then
Cancel = True
End If
Case 45
If MsgBox("This has taken " & Seconds & "seconds. Cancel?", _
vbRetryCancel) = vbCancel Then
Cancel = True
End If
Case 60
'Cancel automatically after 60 seconds.
Cancel = True
End Select
End Sub

Note It is not guaranteed that the ProcessingTimeout event will occur at the intervals specified above. For example, other Visual Basic code running in the background may prevent the event
from occurring. In that case, set the Case statement to a range of values; when the event occurs, set a module-level flag to True, and check it on subsequent occurrences.

Error Event—For Asynchronous Functions


To trap errors that occur when no Visual Basic code is executing (that is, an asynchronous function), use the Error event. For example, if the PrintReport or ExportReport method fails in the
asynchronous stage, the Error event will occur. The example below traps asynchronous errors:

Private Sub DataReport_Error(ByVal JobType As _


MSDataReportLib.AsyncTypeConstants, ByVal Cookie As Long, _
ByVal ErrObj As MSDataReportLib.RptError, ShowError As Boolean)
Select Case JobType ' The JobType identifies the process.
Case rptAsyncPrint
' Trap PrintReport errors here.
Case rptAsyncReport
' Trap ExportReport errors here.
End Select
End Sub

You can also use the Error event to trap specific cases, such as the lack of a printer on the computer, as shown in the code below:

Private Sub DataReport_Error(ByVal JobType As _


MSDataReportLib.AsyncTypeConstants, ByVal Cookie As Long, _
ByVal ErrObj As MSDataReportLib.RptError, ShowError As Boolean)
Select Case ErrObj.ErrorNumber
Case rptErrPrinterInfo ' 8555
MsgBox "A printing error has occurred. " & _
"You may not have a Printer installed."
ShowError = False
Exit Sub
Case Else
' handle other cases here.
ShowError = True
End Select
End Sub

The AsyncProgress Event


The AsyncProgress event is not designed to trap errors, but to allow you to monitor the state of the asynchronous function. By the time this event occurs, all of the data has been processed;
thus two of the event's arguments are PagesCompleted and TotalPages. The event also includes arguments that identify the asynchronous operation: the JobType and Cookie arguments can
then be used to monitor the progress of any process.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconHandlingDataReportErrors.asp (2 of 2) [11/17/2002 11:16:36 PM]


Understanding Control Placement on the Data Report Designer

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer

Visual Basic Concepts

Understanding Control Placement on the Data Report Designer

See Also

Note You will understand this topic better if you read the Data Report tutorial first, beginning at Creating a Simple Data Report.

One way of creating a data report is to:

1. Create a Data Environment designer containing a hierarchy of Command objects.

2. Set the DataSource property of the Data Report designer to the Data Environment designer.

3. Set the DataMember property to the topmost Command object.

4. Right-click the Data Report designer and click Retrieve Structure.

After retrieving the structure, an appropriate number of Group headers and footers will be created, and each header/footer pair is assigned a name that corresponds to a Command object.

5. Drag Command objects from the Data Environment designer to the corresponding section on the Data Report designer.

All of the data fields contained by a Command object are automatically created on the data report as TextBox controls on the section where the Command object is dropped. The DataMember and DataField properties of each TextBox are set in accordance with the
Command object and its data fields.

6. Drag TextBox controls from the section where each was created onto a different section of the Data Report designer.

7. Add Function controls as needed to the report.

When the data report is bound to a data environment, the rules for placement of controls on the report are not immediately apparent. This topic explains how the hierarchy created in the data
environment relates to the system of group headers and footers constructed in the data report.

Command Object Corresponds to Group Header/Footer or Details


Section
With two exceptions, every Command object in the data environment corresponds either to a pair of group header and footer sections, or to the Detail section. The exceptions are discussed later
in this topic.

Hierarchy Versus Headers, Footers, and Detail


The figure below shows a schematic view of the Data Environment designer with four Command objects, each in a parent/child relationship with at least one other command. The data fields that
belong to the table are not shown.

The Data Report designer, on the other hand, is constructed as a series of sections. And each section can be categorized into one of four types: Report header/footers, Page header/footers, Group
header/footers, and the Detail section. For the purposes of instruction, we can disregard the Report and Page header/footer pairs. This leaves the Group headers/footers and the Detail section.

The Detail section, the innermost section of the designer, corresponds to the lowest-level Command object. As you go up through the hierarchy, the Detail section is bracketed by pairs of sections,
with each pair associated with a single Command object. The figure below correlates the Command objects with the sections:

Sections Corresponding to Command Objects

http://msdn.microsoft.com/library/en-us/vbcon98/...trolPlacementOnDataReportDesigner.asp?frame=true (1 of 3) [11/17/2002 11:16:41 PM]


Understanding Control Placement on the Data Report Designer

Thus the figure shows that the hierarchy of the data environment actually corresponds to an expanding series of brackets, with the innermost (Detail) section corresponding to the lowest level of
the hierarchy, and the outermost corresponding to the highest-level Command object.

Controls Can Be Placed in Any Section in a Lower Level


The placement of a control is governed by what section (or pair of sections) it belongs to. In brief, a control can be placed in the section where it originates, and in all sections that are at a level
lower than itself. For example, if a control belongs to the Command1 section pair, it can also be placed in the section pairs for Commands 2, 3, and 4. A second example: A control that originates
in section 3 can also be placed in section 4, but not in sections 1 and 2. Taken to its conclusion, controls that originate in the Command 4 section (the Details section) cannot be placed anywhere
else except in the Details section.

Placing the Function Control

The Function control has three exceptions to the above guidelines regarding control placement. The Function control is not directly bound to the recordset, as is the TextBox control. Instead, the
Function control calculates its value as the report is generated. For this reason, a Function control can only be placed in Footer sections of the report.

A second exception for the Function control: it can only be placed in any section pair that is one level above its own. For example, if the Command 3 object contains a Quantity field, you can place
a Function control that sums the Quantity values onto the footer section for Command 2, or the footer section for Command 1.

The third exception concerning the Function control is this: unlike the other data-bound control (the TextBox control), the Function control can be placed in the Report Footer section. When you do
so, the scope of the control's calculation will be increased to include the whole report. For example, a Function control placed in the Report footer to calculate the sum of the Quantity field will
calculate the sum of every Quantity control on the report.

The Exceptions: Grouping and Grand Total Aggregate

With two exceptions, every Command object in the Data Environment corresponds to a pair of group headers and footers. The first exception occurs when you use the Grouping feature of the Data
Environment designer.

Grouping Fields
When you create grouping fields, the Data Environment designer creates two folders under a single Command object. The first contains the grouping fields, and the second contains the Detail
fields. Even though a new Command object is not created for the grouping fields, you must create a new group header/footer pair on the data report and this requirement qualifies it as an
exception.

Grand Total Aggregate Fields


The second exception occurs when you create a Grand Total aggregate field in the data environment. As happens when creating a grouping field, a new folder is created for the Command object.
The new folder contains any Grand Total aggregate fields created, and you must add a new group header/footer pair to the data report.

For More Information Details about creating aggregate field can be found in "Creating Aggregates" in "Using the Data Environment Designer."

Checking the Hierarchy

If you are in doubt as to the hierarchy of the Data Environment Command objects, you have two ways of ensuring that the data report has the correct group header/footer structure:

Retrieve Structure—If you have not placed many controls onto the Data Report designer, and you can tolerate the restructuring of your data report, use the Retrieve Structure command to
automatically create the right number of group headers and footers.

ADO Hierarchy Information—Right-click the topmost Command object in the Data Environment designer and click Hierarchy Info to display the Hierarchy Information dialog box. Click the
View ADO Hierarchy tab to see a graphical representation of the Command objects' hierarchy.

http://msdn.microsoft.com/library/en-us/vbcon98/...trolPlacementOnDataReportDesigner.asp?frame=true (2 of 3) [11/17/2002 11:16:41 PM]


Understanding Control Placement on the Data Report Designer

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/...trolPlacementOnDataReportDesigner.asp?frame=true (3 of 3) [11/17/2002 11:16:41 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer

MSDN Library GO
Advanced Search Visual Basic Concepts

Understanding Control Placement on the Data Report Designer

See Also

Up One Level Note You will understand this topic better if you read the Data Report tutorial first, beginning at Creating a Simple Data Report.

Parts of the Data Report


Creating a Simple Data Report One way of creating a data report is to:

Exporting a Data Report


Printing the Data Report 1. Create a Data Environment designer containing a hierarchy of Command objects.

2. Set the DataSource property of the Data Report designer to the Data Environment designer.
Data Report Events 3. Set the DataMember property to the topmost Command object.

Understanding Control Placement on the Data Report Designer 4. Right-click the Data Report designer and click Retrieve Structure.

After retrieving the structure, an appropriate number of Group headers and footers will be created, and each header/footer pair is assigned a name that corresponds to a Command object.

5. Drag Command objects from the Data Environment designer to the corresponding section on the Data Report designer.

All of the data fields contained by a Command object are automatically created on the data report as TextBox controls on the section where the Command object is dropped. The DataMember and DataField properties of each TextBox are set in accordance
with the Command object and its data fields.

6. Drag TextBox controls from the section where each was created onto a different section of the Data Report designer.

7. Add Function controls as needed to the report.

When the data report is bound to a data environment, the rules for placement of controls on the report are not immediately apparent. This topic explains how the hierarchy created in the data
environment relates to the system of group headers and footers constructed in the data report.

Command Object Corresponds to Group Header/Footer or Details


Section
With two exceptions, every Command object in the data environment corresponds either to a pair of group header and footer sections, or to the Detail section. The exceptions are discussed
later in this topic.

Hierarchy Versus Headers, Footers, and Detail


The figure below shows a schematic view of the Data Environment designer with four Command objects, each in a parent/child relationship with at least one other command. The data fields
that belong to the table are not shown.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUnderstandingControlPlacementOnDataReportDesigner.asp (1 of 3) [11/17/2002 11:16:43 PM]


Welcome to the MSDN Library
The Data Report designer, on the other hand, is constructed as a series of sections. And each section can be categorized into one of four types: Report header/footers, Page header/footers,
Group header/footers, and the Detail section. For the purposes of instruction, we can disregard the Report and Page header/footer pairs. This leaves the Group headers/footers and the Detail
section.

The Detail section, the innermost section of the designer, corresponds to the lowest-level Command object. As you go up through the hierarchy, the Detail section is bracketed by pairs of
sections, with each pair associated with a single Command object. The figure below correlates the Command objects with the sections:

Sections Corresponding to Command Objects

Thus the figure shows that the hierarchy of the data environment actually corresponds to an expanding series of brackets, with the innermost (Detail) section corresponding to the lowest level
of the hierarchy, and the outermost corresponding to the highest-level Command object.

Controls Can Be Placed in Any Section in a Lower Level


The placement of a control is governed by what section (or pair of sections) it belongs to. In brief, a control can be placed in the section where it originates, and in all sections that are at a
level lower than itself. For example, if a control belongs to the Command1 section pair, it can also be placed in the section pairs for Commands 2, 3, and 4. A second example: A control that
originates in section 3 can also be placed in section 4, but not in sections 1 and 2. Taken to its conclusion, controls that originate in the Command 4 section (the Details section) cannot be
placed anywhere else except in the Details section.

Placing the Function Control

The Function control has three exceptions to the above guidelines regarding control placement. The Function control is not directly bound to the recordset, as is the TextBox control. Instead,
the Function control calculates its value as the report is generated. For this reason, a Function control can only be placed in Footer sections of the report.

A second exception for the Function control: it can only be placed in any section pair that is one level above its own. For example, if the Command 3 object contains a Quantity field, you can
place a Function control that sums the Quantity values onto the footer section for Command 2, or the footer section for Command 1.

The third exception concerning the Function control is this: unlike the other data-bound control (the TextBox control), the Function control can be placed in the Report Footer section. When
you do so, the scope of the control's calculation will be increased to include the whole report. For example, a Function control placed in the Report footer to calculate the sum of the Quantity
field will calculate the sum of every Quantity control on the report.

The Exceptions: Grouping and Grand Total Aggregate

With two exceptions, every Command object in the Data Environment corresponds to a pair of group headers and footers. The first exception occurs when you use the Grouping feature of the
Data Environment designer.

Grouping Fields
When you create grouping fields, the Data Environment designer creates two folders under a single Command object. The first contains the grouping fields, and the second contains the Detail
fields. Even though a new Command object is not created for the grouping fields, you must create a new group header/footer pair on the data report and this requirement qualifies it as an
exception.

Grand Total Aggregate Fields


The second exception occurs when you create a Grand Total aggregate field in the data environment. As happens when creating a grouping field, a new folder is created for the Command
object. The new folder contains any Grand Total aggregate fields created, and you must add a new group header/footer pair to the data report.

For More Information Details about creating aggregate field can be found in "Creating Aggregates" in "Using the Data Environment Designer."

Checking the Hierarchy

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUnderstandingControlPlacementOnDataReportDesigner.asp (2 of 3) [11/17/2002 11:16:43 PM]


Welcome to the MSDN Library
If you are in doubt as to the hierarchy of the Data Environment Command objects, you have two ways of ensuring that the data report has the correct group header/footer structure:

Retrieve Structure—If you have not placed many controls onto the Data Report designer, and you can tolerate the restructuring of your data report, use the Retrieve Structure command to
automatically create the right number of group headers and footers.

ADO Hierarchy Information—Right-click the topmost Command object in the Data Environment designer and click Hierarchy Info to display the Hierarchy Information dialog box. Click
the View ADO Hierarchy tab to see a graphical representation of the Command objects' hierarchy.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUnderstandingControlPlacementOnDataReportDesigner.asp (3 of 3) [11/17/2002 11:16:43 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)

MSDN Library GO
Advanced Search Visual Basic Concepts

Interacting with Data in a Microsoft Jet/Microsoft Access Database

See Also

Up One Level Many data access applications created with earlier versions of Visual Basic store and manage data using the Microsoft Jet database engine, the engine used by Microsoft Access. These
applications use Microsoft Data Access Objects (DAO) to access and manipulate data.
Create a Connection to a Microsoft Jet/Microsoft Access Database File
Create a Data Environment Command Object Now you can use Microsoft ActiveX Data Objects (ADO) to easily manipulate data in a variety of database formats, including Microsoft Jet format. You may still want to use DAO to work with
Create a Simple Data-Bound Form your local Microsoft Jet databases, but for new applications you'll probably want to use ADO and the new data access features of Visual Basic.

Create a Data Grid Form Based on a Query


Topics
Create a Master/Detail Form
Create a Data-Bound Report This series of topics shows you how to use ADO and these new data access features to create a simple database application that interacts with data in the Northwind Traders sample database
(Nwind.mdb). It demonstrates how to:

● Create a connection to a Microsoft Access database file

● Create a data environment Command object

● Create a simple data-bound form

● Create a data grid form based on a query

● Create a master/detail form

● Create a data-bound report

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconConnectToISAMDatabase.asp [11/17/2002 11:17:01 PM]


Create a Connection to a Microsoft Access Database File

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

Visual Basic Concepts

Create a Connection to a Microsoft Access Database File

See Also

When you work with data in a Microsoft Access database, you must first create a connection to a database file. The easiest way to create a connection to a Microsoft Access file is to create a data
environment using the Data Environment designer.

This topic shows how to create a connection to the Northwind Traders sample database (Nwind.mdb). It assumes that the database file is located in the Samples folder on your computer.

To create a connection to a Microsoft Jet/Microsoft Access database file

1. Add a Data Environment designer to your project.

2. Set connection properties for the designer.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

Add a Data Environment Designer to Your Project

A Data Environment designer provides an easy way to create connections to many types of databases. To add a designer to your project, click Add Data Environment on the Project menu. Visual
Basic loads a data environment and adds a Connection object to the data environment.

If the Data Environment designer is not available on the Project menu, add it to your Visual Basic environment. Click Components on the Project menu, click the Designers tab, and then click the
check box next to its name in the list of designers.

Note The first four kinds of ActiveX designers loaded for a project are listed on the Project menu. If more than four designers are loaded, the later ones will be available from the More ActiveX
Designers submenu on the Project menu.

For More Information See Using the Data Environment Designer.

Set Connection Properties

You establish the connection to your data source by setting properties in the Data Link Properties dialog box. To display this dialog box, right-click the Connection object in your data environment
and then choose Properties from the shortcut menu. Select an OLE DB provider on the Provider tab of the dialog box. Then click Next and enter connection information on the Connection tab of the
dialog box. The layout of the Connection tab varies, depending on the OLE DB provider you select on the Provider tab.

For example, to connect to a Microsoft Jet/Microsoft Access database such as the Northwind Traders sample database, select the Microsoft Jet OLE DB provider on the Provider tab. On the
Connection tab, enter the path to the database file; for example:

C:\Samples\Nwind.mdb

If the database file requires you to supply a user name and password, you can also enter those on the Connection tab. You set additional connection properties by clicking the Advanced or All tabs,
or test the connection by clicking Test Connection.

For More Information For more information on connections and connection properties, see Connection Objects in "About the Data Environment Designer." And for more information on Data
Links, see Data Link API Overview in "Database and Messaging Services" in the Platform SDK.

Step by Step

This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb.

To See

Go to the next step Create a Data Environment Command Object

Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreateConnectionToMDBFile.asp?frame=true (1 of 2) [11/17/2002 11:17:04 PM]


Create a Connection to a Microsoft Access Database File

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreateConnectionToMDBFile.asp?frame=true (2 of 2) [11/17/2002 11:17:04 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

MSDN Library GO
Advanced Search Visual Basic Concepts

Create a Connection to a Microsoft Access Database File

See Also

Up One Level When you work with data in a Microsoft Access database, you must first create a connection to a database file. The easiest way to create a connection to a Microsoft Access file is to create a
data environment using the Data Environment designer.
Create a Connection to a Microsoft Jet/Microsoft Access Database File
Create a Data Environment Command Object This topic shows how to create a connection to the Northwind Traders sample database (Nwind.mdb). It assumes that the database file is located in the Samples folder on your computer.
Create a Simple Data-Bound Form
Create a Data Grid Form Based on a Query To create a connection to a Microsoft Jet/Microsoft Access database file
Create a Master/Detail Form
Create a Data-Bound Report 1. Add a Data Environment designer to your project.

2. Set connection properties for the designer.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

Add a Data Environment Designer to Your Project

A Data Environment designer provides an easy way to create connections to many types of databases. To add a designer to your project, click Add Data Environment on the Project menu.
Visual Basic loads a data environment and adds a Connection object to the data environment.

If the Data Environment designer is not available on the Project menu, add it to your Visual Basic environment. Click Components on the Project menu, click the Designers tab, and then click
the check box next to its name in the list of designers.

Note The first four kinds of ActiveX designers loaded for a project are listed on the Project menu. If more than four designers are loaded, the later ones will be available from the More
ActiveX Designers submenu on the Project menu.

For More Information See Using the Data Environment Designer.

Set Connection Properties

You establish the connection to your data source by setting properties in the Data Link Properties dialog box. To display this dialog box, right-click the Connection object in your data
environment and then choose Properties from the shortcut menu. Select an OLE DB provider on the Provider tab of the dialog box. Then click Next and enter connection information on the
Connection tab of the dialog box. The layout of the Connection tab varies, depending on the OLE DB provider you select on the Provider tab.

For example, to connect to a Microsoft Jet/Microsoft Access database such as the Northwind Traders sample database, select the Microsoft Jet OLE DB provider on the Provider tab. On the
Connection tab, enter the path to the database file; for example:

C:\Samples\Nwind.mdb

If the database file requires you to supply a user name and password, you can also enter those on the Connection tab. You set additional connection properties by clicking the Advanced or All
tabs, or test the connection by clicking Test Connection.

For More Information For more information on connections and connection properties, see Connection Objects in "About the Data Environment Designer." And for more information on
Data Links, see Data Link API Overview in "Database and Messaging Services" in the Platform SDK.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateConnectionToMDBFile.asp (1 of 2) [11/17/2002 11:17:06 PM]


Welcome to the MSDN Library
Step by Step

This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb.

To See

Go to the next step Create a Data Environment Command Object

Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateConnectionToMDBFile.asp (2 of 2) [11/17/2002 11:17:06 PM]


Create a Data Environment Command Object

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

Visual Basic Concepts

Create a Data Environment Command Object

See Also

Once you've created a connection to your database, you can use the Data Environment designer to create Command objects that give you access to data. For example, you can create a simple
Command object that gives you access to the data in a table, or a more complex Command object based on a query.

You can then use a data environment Command object as a data source in your application. First, you'll create a simple Command object based on the Customers table in the Northwind Traders
sample database.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

To create a simple data environment Command object

1. Open a Data Environment designer.

2. Create the Command object.

Open a Data Environment Designer

You can open an existing Data Environment designer or create a new one. To open an existing one, click Designers in the Project window, and then double-click the name of the designer. To
create a new one, follow the instructions in the "Create a Connection to a Microsoft Access Database File" topic.

Create the Command Object

Create a data environment Command object by clicking the Add Command button on the Data Environment designer toolbar, or by right-clicking the connection in the data environment window
and choosing Add Command from the menu. You can then specify the Command object's name, the connection it uses, and the source of its data in the Command Properties dialog box. To display
this dialog box, right-click the Command object in your data environment and then choose Properties from the shortcut menu.

For example, to create a Command object based on the Customers table in the Northwind Traders sample database, set the following properties:

Property Setting

Command Name CustomersTable

Connection Connection1

Database Object Table

Object Name Customers

When you click OK, the Data Environment designer displays the Command object and its underlying fields in a hierarchical view in the Data Environment designer window.

The Data Environment designer also creates a Recordset object to represent the records returned by the Command object. The Recordset object uses the same name as the Command object but
adds an "rs" prefix. For example, when the Data Environment designer creates the CustomersTable command, it also creates a Recordset object called "rsCustomersTable."

You can refer to the Command object in code as a method of the data environment, and refer to its recordset as a property of the data environment. For example, if you have created the
CustomersTable command in a data environment called "MyDataEnvironment," you can refer to the command in code as follows:

MyDataEnvironment.CustomersTable

You can refer to the Command object's underlying recordset as follows:

MyDataEnvironment.rsCustomersTable

After you create the Command object, the Auto List Members feature and Object Browser display the command method and recordset property along with the other properties and methods of the
data environment.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreateQueryWithDesigner.asp?frame=true (1 of 2) [11/17/2002 11:17:11 PM]


Create a Data Environment Command Object

For More Information See How Commands are Exposed for Programmatic Access.

Step by Step

This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb.

To See

Go to the next step Create a Simple Data-Bound Form

Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreateQueryWithDesigner.asp?frame=true (2 of 2) [11/17/2002 11:17:11 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

MSDN Library GO
Advanced Search Visual Basic Concepts

Create a Data Environment Command Object

See Also

Up One Level Once you've created a connection to your database, you can use the Data Environment designer to create Command objects that give you access to data. For example, you can create a
simple Command object that gives you access to the data in a table, or a more complex Command object based on a query.
Create a Connection to a Microsoft Jet/Microsoft Access Database File
Create a Data Environment Command Object You can then use a data environment Command object as a data source in your application. First, you'll create a simple Command object based on the Customers table in the Northwind
Create a Simple Data-Bound Form Traders sample database.

Create a Data Grid Form Based on a Query


Create a Master/Detail Form Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.
Create a Data-Bound Report

To create a simple data environment Command object

1. Open a Data Environment designer.

2. Create the Command object.

Open a Data Environment Designer

You can open an existing Data Environment designer or create a new one. To open an existing one, click Designers in the Project window, and then double-click the name of the designer. To
create a new one, follow the instructions in the "Create a Connection to a Microsoft Access Database File" topic.

Create the Command Object

Create a data environment Command object by clicking the Add Command button on the Data Environment designer toolbar, or by right-clicking the connection in the data environment
window and choosing Add Command from the menu. You can then specify the Command object's name, the connection it uses, and the source of its data in the Command Properties dialog
box. To display this dialog box, right-click the Command object in your data environment and then choose Properties from the shortcut menu.

For example, to create a Command object based on the Customers table in the Northwind Traders sample database, set the following properties:

Property Setting

Command Name CustomersTable

Connection Connection1

Database Object Table

Object Name Customers

When you click OK, the Data Environment designer displays the Command object and its underlying fields in a hierarchical view in the Data Environment designer window.

The Data Environment designer also creates a Recordset object to represent the records returned by the Command object. The Recordset object uses the same name as the Command object
but adds an "rs" prefix. For example, when the Data Environment designer creates the CustomersTable command, it also creates a Recordset object called "rsCustomersTable."

You can refer to the Command object in code as a method of the data environment, and refer to its recordset as a property of the data environment. For example, if you have created the
CustomersTable command in a data environment called "MyDataEnvironment," you can refer to the command in code as follows:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateQueryWithDesigner.asp (1 of 2) [11/17/2002 11:17:13 PM]


Welcome to the MSDN Library
MyDataEnvironment.CustomersTable

You can refer to the Command object's underlying recordset as follows:

MyDataEnvironment.rsCustomersTable

After you create the Command object, the Auto List Members feature and Object Browser display the command method and recordset property along with the other properties and methods of
the data environment.

For More Information See How Commands are Exposed for Programmatic Access.

Step by Step

This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb.

To See

Go to the next step Create a Simple Data-Bound Form

Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateQueryWithDesigner.asp (2 of 2) [11/17/2002 11:17:13 PM]


Create a Simple Data-Bound Form

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

Visual Basic Concepts

Create a Simple Data-Bound Form

See Also

Once you've created a Command object in a Data Environment designer to serve as a data source, you can easily create a data-bound form by dragging the Command object onto a blank form.
You can then add a mechanism for navigating through the records that are displayed.

In this topic, you'll create a form that displays records from the Customers table in the Northwind Traders sample database. Then you'll create command buttons for moving to the next or previous
record.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

To create a simple data-bound form

1. Drag a Command object from the Data Environment designer to a blank form.

2. Create command buttons that let you navigate through records.

Drag a Command Object from the Data Environment Designer to a Blank Form

Much of the tedium of creating a data-bound form can be avoided in Visual Basic by dragging a Command object from the Data Environment designer to the form. Visual Basic automatically
creates text box controls to display data from the Command object's recordset and sets data properties that bind the controls to fields in the recordset.

For example, to create a form that displays data from the Customers table in the Northwind Traders sample database, follow the steps in the "Create a Data Environment Command Object" topic
to create a CustomersTable command. Then simply drag the Command object from the Data Environment designer onto a blank form. To view both the form and data environment simultaneously
so you can perform the drag operation, select Tile Horizontally, Tile Vertically, or Cascade from the Window menu.

Create Command Buttons to Navigate through Records

By basing a data-bound form on a data environment Command object's recordset, you can easily create Next and Previous buttons that let you navigate through records. Each command button
requires a single line of code.

For example, to create a Next button for the form that displays customer records, add a command button to the form and change its Caption and Name properties to Next. Then add the following
line to the command button's Next_Click event procedure:

MyDataEnvironment.rsCustomersTable.MoveNext

The code uses the MoveNext method of the CustomersTable command's underlying recordset, rsCustomersTable. It refers to the recordset as a property of the command's data environment
designer, MyDataEnvironment.

Similarly, you can create a Previous button by adding a command button to the form and change its Caption and Name properties to Previous. Then add the following code to the command
button's Previous_Click event procedure:

MyDataEnvironment.rsCustomersTable.MovePrevious

When you run the form, Visual Basic displays the records in the Customers table and lets you move forward and backward through the recordset.

Step by Step

This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb.

To See

Go to the next step Create a Data Grid Form Based on a Query

Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconBindControlsToQueryFields.asp?frame=true (1 of 2) [11/17/2002 11:17:18 PM]


Create a Simple Data-Bound Form

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconBindControlsToQueryFields.asp?frame=true (2 of 2) [11/17/2002 11:17:18 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

MSDN Library GO
Advanced Search Visual Basic Concepts

Create a Simple Data-Bound Form

See Also

Up One Level Once you've created a Command object in a Data Environment designer to serve as a data source, you can easily create a data-bound form by dragging the Command object onto a blank
form. You can then add a mechanism for navigating through the records that are displayed.
Create a Connection to a Microsoft Jet/Microsoft Access Database File
Create a Data Environment Command Object In this topic, you'll create a form that displays records from the Customers table in the Northwind Traders sample database. Then you'll create command buttons for moving to the next or
Create a Simple Data-Bound Form previous record.

Create a Data Grid Form Based on a Query


Create a Master/Detail Form Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.
Create a Data-Bound Report

To create a simple data-bound form

1. Drag a Command object from the Data Environment designer to a blank form.

2. Create command buttons that let you navigate through records.

Drag a Command Object from the Data Environment Designer to a Blank Form

Much of the tedium of creating a data-bound form can be avoided in Visual Basic by dragging a Command object from the Data Environment designer to the form. Visual Basic automatically
creates text box controls to display data from the Command object's recordset and sets data properties that bind the controls to fields in the recordset.

For example, to create a form that displays data from the Customers table in the Northwind Traders sample database, follow the steps in the "Create a Data Environment Command Object"
topic to create a CustomersTable command. Then simply drag the Command object from the Data Environment designer onto a blank form. To view both the form and data environment
simultaneously so you can perform the drag operation, select Tile Horizontally, Tile Vertically, or Cascade from the Window menu.

Create Command Buttons to Navigate through Records

By basing a data-bound form on a data environment Command object's recordset, you can easily create Next and Previous buttons that let you navigate through records. Each command
button requires a single line of code.

For example, to create a Next button for the form that displays customer records, add a command button to the form and change its Caption and Name properties to Next. Then add the
following line to the command button's Next_Click event procedure:

MyDataEnvironment.rsCustomersTable.MoveNext

The code uses the MoveNext method of the CustomersTable command's underlying recordset, rsCustomersTable. It refers to the recordset as a property of the command's data environment
designer, MyDataEnvironment.

Similarly, you can create a Previous button by adding a command button to the form and change its Caption and Name properties to Previous. Then add the following code to the command
button's Previous_Click event procedure:

MyDataEnvironment.rsCustomersTable.MovePrevious

When you run the form, Visual Basic displays the records in the Customers table and lets you move forward and backward through the recordset.

Step by Step
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconBindControlsToQueryFields.asp (1 of 2) [11/17/2002 11:17:19 PM]
Welcome to the MSDN Library

This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb.

To See

Go to the next step Create a Data Grid Form Based on a Query

Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconBindControlsToQueryFields.asp (2 of 2) [11/17/2002 11:17:19 PM]


Create a Data Grid Form Based on a Query

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

Visual Basic Concepts

Create a Data Grid Form Based on a Query

See Also

You can use the same drag-and-drop technique you used to create a simple data-bound form to create a data grid form based on a query. Simply create a Command object based on an SQL
query, then drag the Command object onto a blank form. You can use the Query designer to create the SQL query.

In this topic, you'll create a form that displays orders for French customers in the Northwind Traders sample database in a data grid.

To create a data-bound form based on a query

1. Create a data environment Command object based on a query.

2. Drag the Command object from the data environment designer to a blank form.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

Create a Data Environment Command Object Based on a Query

You can easily create a data environment Command object based on a query by using the Query designer. First, follow the instructions in the previous steps in this scenario to open an existing
Data Environment designer or create a new one.

Create the Command object by clicking the Add Command button on the Data Environment toolbar, or by right-clicking the connection in the Data Environment designer and selecting Add
Command from the menu. You can then specify the Command object's name, the connection it uses, and the source of its data in the Command Properties dialog box. To display this dialog box,
right-click the Command object in your data environment and then choose Properties from the shortcut menu.

For example, to create a Command objects based on a query of orders by French customers in the Northwind Traders sample database, set the following properties:

Property Setting

Command Name FrenchCustomersOrders

Connection Connection1

Rather than select a specific database object as the basis for the command, as you did in the "Create a Data Environment Command Object" step, select SQL Statement as the source of data for
the command. Then click the SQL Builder button to open the Query designer, where you specify the tables, fields, and criteria for the query.

For example, create a query that returns information about orders by French customers by dragging the Customers and Orders tables from the Data View window (available from the View menu)
to the upper pane of the Query designer. (The designer automatically displays a line between the tables showing their related field, CustomerID.) Then click the check box next to the fields that
you want to include in the query:

Table Field

Orders OrderID

Orders CustomerID

Orders OrderDate

Orders ShippedDate

Customers Country

Finally, specify the criteria for the query by entering "France" in the Country field's Criteria box in the Query designer grid. As you specify the fields and criteria, the Query designer automatically
builds the query's underlying SQL statement:

SELECT Orders.OrderID, Orders.CustomerID, Orders.OrderDate, Orders.ShippedDate, Customers.Country


FROM Customers, Orders
WHERE Customers.CustomerID = Orders.CustomerID AND (Customers.Country = 'France')

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconMakeFormFromQuery.asp?frame=true (1 of 2) [11/17/2002 11:17:25 PM]


Create a Data Grid Form Based on a Query

To view the results of the query, right-click the Query designer and select Run. The Query designer displays the resulting recordset.

When you save the query, the Data Environment designer updates the Command object to use the SQL statement as its data source. To verify the statement, you can open the Command
properties dialog box and see the statement is in the SQL Statement box.

For More Information See Designing Queries.

Drag the Command Object from the Data Environment to a Blank Form

In the "Create a Simple Data-Bound Form" topic, you created a data-bound form that displayed data in text boxes by dragging a Command object from the data environment designer to a blank
form. You can also display the data in a data grid by dragging a data environment Command object.

For example, to create a data grid that displays the orders of French customers, select the FrenchCustomersOrders Command object you created in the previous step. Then while pressing the right
mouse button, drag the Command object onto a blank form. Visual Basic displays a popup menu that lets you select whether to create a data grid or bound control. When you select Data Grid,
Visual Basic automatically creates a data grid that displays records from the command's recordset.

When you run the form, Visual Basic displays the records returned by the FrenchCustomersOrders Command object in a data grid.

Step by Step

This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb.

To See

Go to the next step Create a Master/Detail Form

Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconMakeFormFromQuery.asp?frame=true (2 of 2) [11/17/2002 11:17:25 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

MSDN Library GO
Advanced Search Visual Basic Concepts

Create a Data Grid Form Based on a Query

See Also

Up One Level You can use the same drag-and-drop technique you used to create a simple data-bound form to create a data grid form based on a query. Simply create a Command object based on an SQL
query, then drag the Command object onto a blank form. You can use the Query designer to create the SQL query.
Create a Connection to a Microsoft Jet/Microsoft Access Database File
Create a Data Environment Command Object In this topic, you'll create a form that displays orders for French customers in the Northwind Traders sample database in a data grid.
Create a Simple Data-Bound Form
Create a Data Grid Form Based on a Query To create a data-bound form based on a query
Create a Master/Detail Form
Create a Data-Bound Report 1. Create a data environment Command object based on a query.

2. Drag the Command object from the data environment designer to a blank form.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

Create a Data Environment Command Object Based on a Query

You can easily create a data environment Command object based on a query by using the Query designer. First, follow the instructions in the previous steps in this scenario to open an
existing Data Environment designer or create a new one.

Create the Command object by clicking the Add Command button on the Data Environment toolbar, or by right-clicking the connection in the Data Environment designer and selecting Add
Command from the menu. You can then specify the Command object's name, the connection it uses, and the source of its data in the Command Properties dialog box. To display this dialog
box, right-click the Command object in your data environment and then choose Properties from the shortcut menu.

For example, to create a Command objects based on a query of orders by French customers in the Northwind Traders sample database, set the following properties:

Property Setting

Command Name FrenchCustomersOrders

Connection Connection1

Rather than select a specific database object as the basis for the command, as you did in the "Create a Data Environment Command Object" step, select SQL Statement as the source of data
for the command. Then click the SQL Builder button to open the Query designer, where you specify the tables, fields, and criteria for the query.

For example, create a query that returns information about orders by French customers by dragging the Customers and Orders tables from the Data View window (available from the View
menu) to the upper pane of the Query designer. (The designer automatically displays a line between the tables showing their related field, CustomerID.) Then click the check box next to the
fields that you want to include in the query:

Table Field

Orders OrderID

Orders CustomerID

Orders OrderDate

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconMakeFormFromQuery.asp (1 of 2) [11/17/2002 11:17:27 PM]


Welcome to the MSDN Library
Orders ShippedDate

Customers Country

Finally, specify the criteria for the query by entering "France" in the Country field's Criteria box in the Query designer grid. As you specify the fields and criteria, the Query designer
automatically builds the query's underlying SQL statement:

SELECT Orders.OrderID, Orders.CustomerID, Orders.OrderDate, Orders.ShippedDate, Customers.Country


FROM Customers, Orders
WHERE Customers.CustomerID = Orders.CustomerID AND (Customers.Country = 'France')

To view the results of the query, right-click the Query designer and select Run. The Query designer displays the resulting recordset.

When you save the query, the Data Environment designer updates the Command object to use the SQL statement as its data source. To verify the statement, you can open the Command
properties dialog box and see the statement is in the SQL Statement box.

For More Information See Designing Queries.

Drag the Command Object from the Data Environment to a Blank Form

In the "Create a Simple Data-Bound Form" topic, you created a data-bound form that displayed data in text boxes by dragging a Command object from the data environment designer to a
blank form. You can also display the data in a data grid by dragging a data environment Command object.

For example, to create a data grid that displays the orders of French customers, select the FrenchCustomersOrders Command object you created in the previous step. Then while pressing the
right mouse button, drag the Command object onto a blank form. Visual Basic displays a popup menu that lets you select whether to create a data grid or bound control. When you select
Data Grid, Visual Basic automatically creates a data grid that displays records from the command's recordset.

When you run the form, Visual Basic displays the records returned by the FrenchCustomersOrders Command object in a data grid.

Step by Step

This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb.

To See

Go to the next step Create a Master/Detail Form

Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconMakeFormFromQuery.asp (2 of 2) [11/17/2002 11:17:27 PM]


Create a Master Detail Report on a Form

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

Visual Basic Concepts

Create a Master/Detail Form

See Also

In database applications, it's often useful to simultaneously view a record with a group of related records. For example, you may want to view a customer record and the current orders for the
customer. A common way to accomplish this is to create a master/detail form.

To create a Master/Detail form

1. Create a parent/child data environment Command object.

2. Drag the Command object from the Data Environment designer to a blank form.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

Create a Parent/Child Data Environment Command Object

You've seen in the "Create a Data Environment Command Object" and "Create a Data Grid Form Based on a Query" topics how to create a data environment Command object based on a single
table or query. You can also use a hierarchical parent/child Command object that lets you simultaneously view a record from one table or query with a group of related records in a second table or
query.

For example, you can create a parent Command object that returns address information for all French customers in the Northwind Traders sample database. You can then add a related child
Command object to the parent Command object that displays order information for each French customer.

Create the parent Command object by following the instructions in the previous steps in this scenario to open an existing Data Environment designer or create a new one. Then click the Add
Command button on the Data Environment toolbar and set the following properties in the Command Properties dialog box:

Property Setting

Command Name FrenchCustomers

Connection Connection1

Select SQL Statement as the source of data for the Command object. Click the SQL Builder button to open the Query designer, drag the Customers table from the Data View window to the upper
pane of the Query designer, and then click the check box next to the CustomerID, CompanyName, Address, City, PostalCode, and Country fields. Specify the criteria for the query by entering
"France" in the Country field's Criteria box. The Query designer builds the following SQL statement:

SELECT CustomerID, CompanyName, Address, City, PostalCode, Country


FROM Customers
WHERE (Country = 'France')

Add the child command to the parent command by right-clicking the FrenchCustomers command in the Data Environment designer, and then select Add Child Command from the popup menu. Set
the following properties in the Command Properties dialog box:

Property Setting

Command Name OrderDates

Connection Connection1

Select SQL Statement as the source of data for the Command object. Click the SQL Builder button to open the Query designer, drag the Orders table from the Data View window to the upper pane
of the Query designer, and then click the check box next to the OrderID, CustomerID, OrderDate, and ShippedDate fields. The Query designer builds the following SQL statement:

SELECT OrderID, CustomerID, OrderDate, ShippedDate


FROM Orders

Finally, define the relationship between the parent and child Command objects. In the Data Environment designer, select the OrderDates Command object and click the Properties button on the
toolbar. Click the Relation tab. Define a relationship between the CustomerID fields in the parent and child Command objects by selecting CustomerID in the Parent Fields and Child
Fields/Parameters lists. Then click the Add button. The Data Environment designer adds the relation to the Relation Definition box.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreateDetailReportOnForm.asp?frame=true (1 of 2) [11/17/2002 11:17:34 PM]


Create a Master Detail Report on a Form

When you've finished, the data environment displays a hierarchical view of the parent Command object and its fields along with the child Command object and its fields.

For More Information See How Commands are Exposed for Programmatic Access.

Drag the Command Object from the Data Environment to a Blank Form

As with the data-bound forms based on a single table or query, you can create a master/detail form based on a hierarchical parent/child Command object by simply dragging the Command object
from the Data Environment designer to a blank form.

For example, create a master/detail form that displays address information and related order information for French customers by selecting the FrenchCustomers Command object you created in
the previous step. Then while pressing the right mouse button, drag the Command object onto a blank form. Visual Basic displays a popup menu that lets you select whether to create a data grid,
hierarchical flexgrid, or bound controls. When you select hierarchical flexgrid, Visual Basic automatically creates a master/detail form based on the parent/child Command object.

When you run the form, Visual Basic displays the address records returned by the FrenchCustomers Command object and related order records returned by the OrderDates Command object.

Step by Step

This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb.

To See

Go to the next step Create a Data-Bound Report

Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreateDetailReportOnForm.asp?frame=true (2 of 2) [11/17/2002 11:17:34 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

MSDN Library GO
Advanced Search Visual Basic Concepts

Create a Master/Detail Form

See Also

Up One Level In database applications, it's often useful to simultaneously view a record with a group of related records. For example, you may want to view a customer record and the current orders for the
customer. A common way to accomplish this is to create a master/detail form.
Create a Connection to a Microsoft Jet/Microsoft Access Database File
Create a Data Environment Command Object To create a Master/Detail form
Create a Simple Data-Bound Form
Create a Data Grid Form Based on a Query 1. Create a parent/child data environment Command object.

Create a Master/Detail Form 2. Drag the Command object from the Data Environment designer to a blank form.

Create a Data-Bound Report


Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

Create a Parent/Child Data Environment Command Object

You've seen in the "Create a Data Environment Command Object" and "Create a Data Grid Form Based on a Query" topics how to create a data environment Command object based on a
single table or query. You can also use a hierarchical parent/child Command object that lets you simultaneously view a record from one table or query with a group of related records in a
second table or query.

For example, you can create a parent Command object that returns address information for all French customers in the Northwind Traders sample database. You can then add a related child
Command object to the parent Command object that displays order information for each French customer.

Create the parent Command object by following the instructions in the previous steps in this scenario to open an existing Data Environment designer or create a new one. Then click the Add
Command button on the Data Environment toolbar and set the following properties in the Command Properties dialog box:

Property Setting

Command Name FrenchCustomers

Connection Connection1

Select SQL Statement as the source of data for the Command object. Click the SQL Builder button to open the Query designer, drag the Customers table from the Data View window to the
upper pane of the Query designer, and then click the check box next to the CustomerID, CompanyName, Address, City, PostalCode, and Country fields. Specify the criteria for the query by
entering "France" in the Country field's Criteria box. The Query designer builds the following SQL statement:

SELECT CustomerID, CompanyName, Address, City, PostalCode, Country


FROM Customers
WHERE (Country = 'France')

Add the child command to the parent command by right-clicking the FrenchCustomers command in the Data Environment designer, and then select Add Child Command from the popup
menu. Set the following properties in the Command Properties dialog box:

Property Setting

Command Name OrderDates

Connection Connection1

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateDetailReportOnForm.asp (1 of 2) [11/17/2002 11:17:35 PM]


Welcome to the MSDN Library

Select SQL Statement as the source of data for the Command object. Click the SQL Builder button to open the Query designer, drag the Orders table from the Data View window to the upper
pane of the Query designer, and then click the check box next to the OrderID, CustomerID, OrderDate, and ShippedDate fields. The Query designer builds the following SQL statement:

SELECT OrderID, CustomerID, OrderDate, ShippedDate


FROM Orders

Finally, define the relationship between the parent and child Command objects. In the Data Environment designer, select the OrderDates Command object and click the Properties button on
the toolbar. Click the Relation tab. Define a relationship between the CustomerID fields in the parent and child Command objects by selecting CustomerID in the Parent Fields and Child
Fields/Parameters lists. Then click the Add button. The Data Environment designer adds the relation to the Relation Definition box.

When you've finished, the data environment displays a hierarchical view of the parent Command object and its fields along with the child Command object and its fields.

For More Information See How Commands are Exposed for Programmatic Access.

Drag the Command Object from the Data Environment to a Blank Form

As with the data-bound forms based on a single table or query, you can create a master/detail form based on a hierarchical parent/child Command object by simply dragging the Command
object from the Data Environment designer to a blank form.

For example, create a master/detail form that displays address information and related order information for French customers by selecting the FrenchCustomers Command object you created
in the previous step. Then while pressing the right mouse button, drag the Command object onto a blank form. Visual Basic displays a popup menu that lets you select whether to create a
data grid, hierarchical flexgrid, or bound controls. When you select hierarchical flexgrid, Visual Basic automatically creates a master/detail form based on the parent/child Command object.

When you run the form, Visual Basic displays the address records returned by the FrenchCustomers Command object and related order records returned by the OrderDates Command object.

Step by Step

This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb.

To See

Go to the next step Create a Data-Bound Report

Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateDetailReportOnForm.asp (2 of 2) [11/17/2002 11:17:35 PM]


Create a Data-Bound Report

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

Visual Basic Concepts

Create a Data-Bound Report

See Also

You can create a data-bound report using the same drag-and-drop technique you used to create data-bound forms. Simply create a Command object based on a table or query, then drag it onto a
blank report in the Data Report designer.

In this topic, you'll create a report that displays orders for French customers in the Northwind Traders sample database.

To create a data-bound report

1. Create a data environment Command object.

2. Open a Data Report designer.

3. Drag the Command object from the Data Environment designer to the Data Report designer.

4. Set data properties for the report.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

Create a Data Environment Command

You can follow the steps in the "Create a Data Environment Command Object" topic to create a command based on a table or in the "Create a Data Grid Form Based on a Query" to create a
command based on a query. In this topic, you'll base the report on the FrenchCustomersOrders command you created in the "Create a Data Grid Form Based on a Query" topic.

Open a Data Report Designer

The Data Report designer lets you easily create reports from within the Visual Basic environment. You can use the Data Report designer to create a multiple-section data report, add controls to the
report, and bind the report to data. You can also drag Command objects from the Data Environment designer to the Data Report designer.

To add a data report to your project, click Add Data Report on the Project menu. If the Data Report designer is not available on the Project menu, add it to your Visual Basic environment. Click
Components on the Project menu, click the Designers tab, and then click the check box next to its name in the list of designers.

Note The first four kinds of ActiveX designers loaded for a project are listed on the Project menu. If more than four designers are loaded, the later ones will be available from the More ActiveX
Designers submenu on the Project menu.

For More Information See Writing Reports with the Microsoft Data Report Designer.

Drag the Command from the Data Environment to the Data Report

Dragging a data environment Command object onto a Data Report designer is similar to dragging it onto a form. When you drop the Command object onto the report's Detail section, the Data
Report designer automatically creates controls to display data from the Command object's recordset and sets data properties that bind the controls to fields in the recordset.

For example, to create a report that displays the orders of French customers, select the FrenchCustomersOrders Command object you created in the "Create a Data Grid Form Based on a Query"
topic. Then drag the Command object onto the detail section of a blank report.

Set Data Properties for the Report

When you drag a Command objectfrom the Data Environment, the Data Report designer automatically sets data properties for each control that it creates. However, before the report can display
data, you must also set the report's DataSource and DataMember properties.

For example, to display the orders of French Customers, set the properties as follows:

Property Setting

DataMember FrenchCustomersOrders

DataSource MyDataEnvironment

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconMakeReportUsingDesigner.asp?frame=true (1 of 2) [11/17/2002 11:17:39 PM]


Create a Data-Bound Report

When you run the report, the Data Report designer creates a report based on the records returned by the FrenchCustomersOrders Command object.

Step by Step

This topic concludes a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. To start from the beginning, see Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconMakeReportUsingDesigner.asp?frame=true (2 of 2) [11/17/2002 11:17:39 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database

MSDN Library GO
Advanced Search Visual Basic Concepts

Create a Data-Bound Report

See Also

Up One Level You can create a data-bound report using the same drag-and-drop technique you used to create data-bound forms. Simply create a Command object based on a table or query, then drag it
onto a blank report in the Data Report designer.
Create a Connection to a Microsoft Jet/Microsoft Access Database File
Create a Data Environment Command Object In this topic, you'll create a report that displays orders for French customers in the Northwind Traders sample database.
Create a Simple Data-Bound Form
Create a Data Grid Form Based on a Query To create a data-bound report
Create a Master/Detail Form
Create a Data-Bound Report 1. Create a data environment Command object.

2. Open a Data Report designer.

3. Drag the Command object from the Data Environment designer to the Data Report designer.

4. Set data properties for the report.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. It begins with the topic, Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

Create a Data Environment Command

You can follow the steps in the "Create a Data Environment Command Object" topic to create a command based on a table or in the "Create a Data Grid Form Based on a Query" to create a
command based on a query. In this topic, you'll base the report on the FrenchCustomersOrders command you created in the "Create a Data Grid Form Based on a Query" topic.

Open a Data Report Designer

The Data Report designer lets you easily create reports from within the Visual Basic environment. You can use the Data Report designer to create a multiple-section data report, add controls
to the report, and bind the report to data. You can also drag Command objects from the Data Environment designer to the Data Report designer.

To add a data report to your project, click Add Data Report on the Project menu. If the Data Report designer is not available on the Project menu, add it to your Visual Basic environment.
Click Components on the Project menu, click the Designers tab, and then click the check box next to its name in the list of designers.

Note The first four kinds of ActiveX designers loaded for a project are listed on the Project menu. If more than four designers are loaded, the later ones will be available from the More
ActiveX Designers submenu on the Project menu.

For More Information See Writing Reports with the Microsoft Data Report Designer.

Drag the Command from the Data Environment to the Data Report

Dragging a data environment Command object onto a Data Report designer is similar to dragging it onto a form. When you drop the Command object onto the report's Detail section, the Data
Report designer automatically creates controls to display data from the Command object's recordset and sets data properties that bind the controls to fields in the recordset.

For example, to create a report that displays the orders of French customers, select the FrenchCustomersOrders Command object you created in the "Create a Data Grid Form Based on a
Query" topic. Then drag the Command object onto the detail section of a blank report.

Set Data Properties for the Report

When you drag a Command objectfrom the Data Environment, the Data Report designer automatically sets data properties for each control that it creates. However, before the report can

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconMakeReportUsingDesigner.asp (1 of 2) [11/17/2002 11:17:41 PM]


Welcome to the MSDN Library
display data, you must also set the report's DataSource and DataMember properties.

For example, to display the orders of French Customers, set the properties as follows:

Property Setting

DataMember FrenchCustomersOrders

DataSource MyDataEnvironment

When you run the report, the Data Report designer creates a report based on the records returned by the FrenchCustomersOrders Command object.

Step by Step

This topic concludes a series that walks you through creating a simple database application that interacts with data in Nwind.mdb. To start from the beginning, see Interacting with Data in a
Microsoft Jet/Microsoft Access Database.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconMakeReportUsingDesigner.asp (2 of 2) [11/17/2002 11:17:41 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating a DHTML Application that Interacts with SQL Server Data

See Also

Up One Level Visual Basic lets you easily create applications that use the Internet or a corporate intranet to interact with data in a distributed relational database system such as SQL Server. For example,
you can create an application that uses an HTML page for data entry or to query data in your database.
Add a Table to an SQL Server Database
Create a Data Entry HTML Page Topics
Create an HTML Page for Viewing and Updating Data
Create an HTML Page that Runs a Stored Procedure This scenario shows you how to create a DHTML application that interacts with data in the Pubs sample database in SQL Server. It is designed for use on an intranet and requires that you view
HTML pages using Microsoft Internet Explorer 4.x. The scenario demonstrates:

● Adding a table to an SQL Server database

● Creating a data entry HTML page

● Creating an HTML page for viewing and updating data

● Creating an HTML page that runs a stored procedure

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconQuerySQLServerDatabase.asp [11/17/2002 11:17:50 PM]


Adding a Table to an SQL Server Database

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server Data

Visual Basic Concepts

Adding a Table to an SQL Server Database

See Also

When you create a DHTML application that interacts with a SQL Server database, you may want to add new tables to the database. You can use a data environment to create a connection to the
SQL Server database, then create your tables in the Data View window.

This topic shows how to create a connection to the Pubs sample database in SQL Server, and how to add a new Customers table to the database.

To add a table to an SQL database

1. Open a new DHTML Application DLL project.

2. Create a connection to an SQL Server database.

3. Add a table to the database.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in an SQL Server database. It begins with the topic Creating a DHTML
Application that Interacts with SQL Server Data.

Open a DHTML Application DLL Project


The first step in creating a DHTML application is to open a new DHTML Application DLL project. A DHTML Application DLL project is an ActiveX DLL project template that automatically loads the
DHTML Page designer and its HTML toolbox tab and HTML controls, which are known as elements. Select New Project from the File menu, then select DHTML Application in the New Project dialog
box.

Visual Basic automatically adds a DHTML Page designer to your project. For every HTML page in your application, you need a corresponding designer. Open the Designers folder in the Project
Explorer and double-click DHTMLPage1. The DHTML Page designer displays the page's interface in the right pane of the designer window, and a hierarchical list of the objects on the page in the left
pane of the window.

For More Information For more information on creating a DHTML application, see Developing DHTML Applications in Building Internet Applications in the Component Tools Guide.

Create a Connection to an SQL Server Database


A data environment provides an easy way to create a connection to a database. To add a data environment to your project, select Add Data Environment from the Project menu. Visual Basic loads
a data environment, and adds a Connection object to the data environment.

You establish the connection to your data source by setting properties in the Data Link Properties dialog box. To display this dialog box, right-click the Connection object in your data environment
and then choose Properties from the menu. Select an OLE DB provider on the Provider tab of the dialog box. Then click Next and enter connection information on the Connection tab of the dialog
box. The layout of the Connection tab varies, depending on the OLE DB provider you select on the Provider tab.

For example, to connect to an SQL Server database such as the Pubs sample database, select the Microsoft OLE DB Provider for SQL Server on the Provider tab. On the Connection tab, enter the
server name, log on information, and the database name or SQL database file name.

You set additional connection properties by clicking the Advanced or All tabs, or test the connection by clicking Test Connection.

For More Information For more information on using the Data Environment, see Chapter 3, About the Data Environment Designer. For more information on connections and connection
properties, see Connection Objects in "About the Data Environment Designer." And for more information on Data Links, see Data Link API Overview in "Database and Messaging Services" in the
Platform SDK.

Add a Table to the Database


The Data View window lets you easily add a table, view, or stored procedure to your database. Open the Data View window by clicking the Data View Window button on the Standard toolbar. The
Data View window displays a hierarchical view of any database connections you've created. For example, if you've created a connection to the Pubs sample database, the Data View window shows
the database and its diagrams, tables, views, and stored procedures.

Add a table to the database by right-clicking the Tables folder in the Data View window and selecting the New Table command. The Data View window displays the Choose Name dialog box, where
you enter a name for the table. When you click OK, the Data View window displays the New Table window, where you enter the table definition — the name of each column in the table, its
datatype, and other information about the column. To specify a primary key for the table, disable the Allow Nulls box, right-click the cell, and select Set Primary Key from the shortcut menu.

http://msdn.microsoft.com/library/en-us/vbcon98/...l/vbconConnectToSQLServerDatabase.asp?frame=true (1 of 2) [11/17/2002 11:17:53 PM]


Adding a Table to an SQL Server Database

For example, to add a Customers table to the Pubs database that stores customer address information, enter Customers in the Choose Name dialog box and enter the following table definition:

Column Name Datatype Length

CustomerID char 5

CompanyName varchar 20

Address varchar 40

City varchar 20

Region varchar 10

PostalCode varchar 10

Country varchar 20

Set CustomerID as the primary key. When you save the table definition, the table is added to the database.

For More Information For more information on using the Data View window, see Managing Databases in Data View. For more information on using the Data View window to create a table, see
Tables.

Step by Step

This topic is part of a series that walks you through creating a simple DHTML application that interacts with data in an SQL Server database.

To See

Go to the next step Create a Data Entry HTML Page

Start from the beginning Creating a DHTML Application that Interacts with SQL Server Data

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/...l/vbconConnectToSQLServerDatabase.asp?frame=true (2 of 2) [11/17/2002 11:17:53 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server Data

MSDN Library GO
Advanced Search Visual Basic Concepts

Adding a Table to an SQL Server Database

See Also

Up One Level When you create a DHTML application that interacts with a SQL Server database, you may want to add new tables to the database. You can use a data environment to create a connection to
the SQL Server database, then create your tables in the Data View window.
Add a Table to an SQL Server Database
Create a Data Entry HTML Page This topic shows how to create a connection to the Pubs sample database in SQL Server, and how to add a new Customers table to the database.
Create an HTML Page for Viewing and Updating Data
Create an HTML Page that Runs a Stored Procedure To add a table to an SQL database

1. Open a new DHTML Application DLL project.

2. Create a connection to an SQL Server database.

3. Add a table to the database.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in an SQL Server database. It begins with the topic Creating a DHTML
Application that Interacts with SQL Server Data.

Open a DHTML Application DLL Project


The first step in creating a DHTML application is to open a new DHTML Application DLL project. A DHTML Application DLL project is an ActiveX DLL project template that automatically loads the
DHTML Page designer and its HTML toolbox tab and HTML controls, which are known as elements. Select New Project from the File menu, then select DHTML Application in the New Project
dialog box.

Visual Basic automatically adds a DHTML Page designer to your project. For every HTML page in your application, you need a corresponding designer. Open the Designers folder in the Project
Explorer and double-click DHTMLPage1. The DHTML Page designer displays the page's interface in the right pane of the designer window, and a hierarchical list of the objects on the page in
the left pane of the window.

For More Information For more information on creating a DHTML application, see Developing DHTML Applications in Building Internet Applications in the Component Tools Guide.

Create a Connection to an SQL Server Database


A data environment provides an easy way to create a connection to a database. To add a data environment to your project, select Add Data Environment from the Project menu. Visual Basic
loads a data environment, and adds a Connection object to the data environment.

You establish the connection to your data source by setting properties in the Data Link Properties dialog box. To display this dialog box, right-click the Connection object in your data
environment and then choose Properties from the menu. Select an OLE DB provider on the Provider tab of the dialog box. Then click Next and enter connection information on the Connection
tab of the dialog box. The layout of the Connection tab varies, depending on the OLE DB provider you select on the Provider tab.

For example, to connect to an SQL Server database such as the Pubs sample database, select the Microsoft OLE DB Provider for SQL Server on the Provider tab. On the Connection tab, enter
the server name, log on information, and the database name or SQL database file name.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconConnectToSQLServerDatabase.asp (1 of 2) [11/17/2002 11:17:55 PM]


Welcome to the MSDN Library
You set additional connection properties by clicking the Advanced or All tabs, or test the connection by clicking Test Connection.

For More Information For more information on using the Data Environment, see Chapter 3, About the Data Environment Designer. For more information on connections and connection
properties, see Connection Objects in "About the Data Environment Designer." And for more information on Data Links, see Data Link API Overview in "Database and Messaging Services" in
the Platform SDK.

Add a Table to the Database


The Data View window lets you easily add a table, view, or stored procedure to your database. Open the Data View window by clicking the Data View Window button on the Standard toolbar.
The Data View window displays a hierarchical view of any database connections you've created. For example, if you've created a connection to the Pubs sample database, the Data View
window shows the database and its diagrams, tables, views, and stored procedures.

Add a table to the database by right-clicking the Tables folder in the Data View window and selecting the New Table command. The Data View window displays the Choose Name dialog box,
where you enter a name for the table. When you click OK, the Data View window displays the New Table window, where you enter the table definition — the name of each column in the table,
its datatype, and other information about the column. To specify a primary key for the table, disable the Allow Nulls box, right-click the cell, and select Set Primary Key from the shortcut
menu.

For example, to add a Customers table to the Pubs database that stores customer address information, enter Customers in the Choose Name dialog box and enter the following table definition:

Column Name Datatype Length

CustomerID char 5

CompanyName varchar 20

Address varchar 40

City varchar 20

Region varchar 10

PostalCode varchar 10

Country varchar 20

Set CustomerID as the primary key. When you save the table definition, the table is added to the database.

For More Information For more information on using the Data View window, see Managing Databases in Data View. For more information on using the Data View window to create a table,
see Tables.

Step by Step

This topic is part of a series that walks you through creating a simple DHTML application that interacts with data in an SQL Server database.

To See

Go to the next step Create a Data Entry HTML Page

Start from the beginning Creating a DHTML Application that Interacts with SQL Server Data

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconConnectToSQLServerDatabase.asp (2 of 2) [11/17/2002 11:17:55 PM]


Creating a Data Entry HTML Page

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server Data

Visual Basic Concepts

Creating a Data Entry HTML Page

See Also

Visual Basic lets you easily create an HTML page that you can use to enter records in an SQL Server database. You can use the DHTML Page designer to create the HTML page and a data
environment Command object to establish a connection to the database. You can write code that uses ActiveX Data Objects (ADO) to handle data processing.

This topic shows how to create an HTML page to enter data in the Customers table you created in the "Adding a Table to an SQL Server Database" topic. It shows how to use the data environment
and ADO code to pass data from the HTML page to the table.

To create a data entry HTML page

1. Add labels and TextField elements to an HTML page.

2. Create a data environment Command object.

3. Add a Button element to the page to append records to a table.

4. Load the HTML page.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in an SQL Server database. It begins with the topic Creating a DHTML
Application that Interacts with SQL Server Data.

Add Labels and TextField Elements to an HTML Page


You can use the DHTML Page designer to design your HTML page. Double-click the DHTML Page designer icon in the Project Explorer to bring up the designer. To add a label to a page, simply click
in the right pane of the designer window and type the label text. To add a TextField element to the page, select the element from the toolbox and drag it to the right pane of the designer window.

For example, you can create a data entry HTML page that lets you enter address information in the new Customers table in the Pubs sample database. First, type "Customer ID:" in the right pane
of the designer window to serve as a label for a Customer ID TextField element, then drag a TextField element next to the label, set its Name and ID properties to CustomerID, and clear its Value
property. Repeat the same process for CompanyName, Address, City, Region, PostalCode, and Country elements.

For More Information For more information on using the DHTML Page designer, see Designing Pages for DHTML Applications in Chapter 2, "Developing DHTML Applications" of Building Internet
Applications in the Component Tools Guide.

Create a Data Environment Command Object


As you saw in the "Interact with Data in a Microsoft Jet/Microsoft Access Database" scenario, a data environment Command object can give you access to a table's data. In a DHTML application, a
data environment Command object can serve as a logical "middle tier," linking a data source with data displayed on an HTML page.

Create the Command object by clicking the Add Command button on the Data Environment toolbar, or by right-clicking the connection in the Data Environment designer and selecting Add
Command from the shortcut menu. You can then specify the Command object's name, the connection it uses, and the source of its data in the Command Properties dialog box. To display this
dialog box, right-click the Command object in your data environment and then choose Properties from the menu..

For example, you can create a data environment Command object that provides access to the new Customers table in the Pubs sample database. Set the following properties, using the connection
to the Pubs sample database that you created in the "Adding a Table to an SQL Server Database" topic:

Property Setting

Command Name Customers

Connection Connection1

Database Object Table

Object Name dbo.customers

To enable updating of records in the Customers table, change the default lock type used by the command. Click the Advanced tab in the Command Properties dialog box and set the Lock Type
property to Optimistic.

For More Information For more information on creating a data environment Command object, see Command Objects in "About the Data Environment Designer."

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreateDataInputForm.asp?frame=true (1 of 2) [11/17/2002 11:17:59 PM]


Creating a Data Entry HTML Page

Add a Button Element to the Page to Append Records to a Table


To provide a way to append the data entered on the HTML page to a table, you can add a Button element to the HTML page by dragging a Button element to the right pane of the DHTML Page
designer. For example, you can add a Button element that appends address information to the Customers table. First, drag a Button element to the right pane of the designer window, and then set
its name and id properties to AddCustomer.

Using the data environment and ADO, you can easily append records to a table in an SQL database. Refer to the data entered in an HTML page's TextField elements using the element's Value
property, then use ADO code to append the data to the corresponding field in the table. The recordset underlying a data environment Command object can provide the "middle tier" between the
table and the HTML page.

For example, to enable the data entry HTML page for the new Customers table in the Pubs sample database, add the following code to the onclick event procedure for the DHTML Page object's
AddCustomer Button element:

Private Function AddCustomer_onclick() As Boolean

' Run the Customers Command object.


MyDataEnvironment.Customers

' Append values from the DHTML Page object's elements


' to the command's underlying recordset.
With MyDataEnvironment.rsCustomers
.AddNew
!CustomerID = CustomerID.Value
!CompanyName = CompanyName.Value
!Address = Address.Value
!City = City.Value
!Region = Region.Value
!PostalCode = PostalCode.Value
!Country = Country.Value
.Update
.Close
End With

' Clear the elements.


CustomerID.Value = ""
CompanyName.Value = ""
Address.Value = ""
City.Value = ""
Region.Value = ""
PostalCode.Value = ""
Country.Value = ""

End Function

For More Information For more information on using ADO, see ADO, DAO and RDO in Visual Basic.

Load the HTML Page


To view the finished page in Internet Explorer, press F5 or click the Start button on the toolbar. You can also explicitly make a dynamic-link library and HTML page for the project by setting
properties on the Make tab of the Project Properties dialog box, then selecting Make .dll from the File menu.

For More Information For more information on testing your DHTML applications, see Testing Your DHTML Application in Chapter 2, "Developing DHTML Applications" in Building Internet
Applications in the Component Tools Guide.

Step by Step

This topic is part of a series that walks you through creating a simple DHTML application that interacts with data in an SQL Server database.

To See

Go to the next step Creating an HTML Page for Viewing and Updating Data

Start from the beginning Creating a DHTML Application that Interacts with SQL Server Data

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreateDataInputForm.asp?frame=true (2 of 2) [11/17/2002 11:17:59 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server Data

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating a Data Entry HTML Page

See Also

Up One Level Visual Basic lets you easily create an HTML page that you can use to enter records in an SQL Server database. You can use the DHTML Page designer to create the HTML page and a data
environment Command object to establish a connection to the database. You can write code that uses ActiveX Data Objects (ADO) to handle data processing.
Add a Table to an SQL Server Database
Create a Data Entry HTML Page This topic shows how to create an HTML page to enter data in the Customers table you created in the "Adding a Table to an SQL Server Database" topic. It shows how to use the data
Create an HTML Page for Viewing and Updating Data environment and ADO code to pass data from the HTML page to the table.

Create an HTML Page that Runs a Stored Procedure


To create a data entry HTML page

1. Add labels and TextField elements to an HTML page.

2. Create a data environment Command object.

3. Add a Button element to the page to append records to a table.

4. Load the HTML page.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in an SQL Server database. It begins with the topic Creating a DHTML
Application that Interacts with SQL Server Data.

Add Labels and TextField Elements to an HTML Page


You can use the DHTML Page designer to design your HTML page. Double-click the DHTML Page designer icon in the Project Explorer to bring up the designer. To add a label to a page, simply
click in the right pane of the designer window and type the label text. To add a TextField element to the page, select the element from the toolbox and drag it to the right pane of the designer
window.

For example, you can create a data entry HTML page that lets you enter address information in the new Customers table in the Pubs sample database. First, type "Customer ID:" in the right
pane of the designer window to serve as a label for a Customer ID TextField element, then drag a TextField element next to the label, set its Name and ID properties to CustomerID, and clear
its Value property. Repeat the same process for CompanyName, Address, City, Region, PostalCode, and Country elements.

For More Information For more information on using the DHTML Page designer, see Designing Pages for DHTML Applications in Chapter 2, "Developing DHTML Applications" of Building
Internet Applications in the Component Tools Guide.

Create a Data Environment Command Object


As you saw in the "Interact with Data in a Microsoft Jet/Microsoft Access Database" scenario, a data environment Command object can give you access to a table's data. In a DHTML
application, a data environment Command object can serve as a logical "middle tier," linking a data source with data displayed on an HTML page.

Create the Command object by clicking the Add Command button on the Data Environment toolbar, or by right-clicking the connection in the Data Environment designer and selecting Add
Command from the shortcut menu. You can then specify the Command object's name, the connection it uses, and the source of its data in the Command Properties dialog box. To display this
dialog box, right-click the Command object in your data environment and then choose Properties from the menu..

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateDataInputForm.asp (1 of 3) [11/17/2002 11:18:01 PM]


Welcome to the MSDN Library
For example, you can create a data environment Command object that provides access to the new Customers table in the Pubs sample database. Set the following properties, using the
connection to the Pubs sample database that you created in the "Adding a Table to an SQL Server Database" topic:

Property Setting

Command Name Customers

Connection Connection1

Database Object Table

Object Name dbo.customers

To enable updating of records in the Customers table, change the default lock type used by the command. Click the Advanced tab in the Command Properties dialog box and set the Lock Type
property to Optimistic.

For More Information For more information on creating a data environment Command object, see Command Objects in "About the Data Environment Designer."

Add a Button Element to the Page to Append Records to a Table


To provide a way to append the data entered on the HTML page to a table, you can add a Button element to the HTML page by dragging a Button element to the right pane of the DHTML Page
designer. For example, you can add a Button element that appends address information to the Customers table. First, drag a Button element to the right pane of the designer window, and
then set its name and id properties to AddCustomer.

Using the data environment and ADO, you can easily append records to a table in an SQL database. Refer to the data entered in an HTML page's TextField elements using the element's Value
property, then use ADO code to append the data to the corresponding field in the table. The recordset underlying a data environment Command object can provide the "middle tier" between
the table and the HTML page.

For example, to enable the data entry HTML page for the new Customers table in the Pubs sample database, add the following code to the onclick event procedure for the DHTML Page object's
AddCustomer Button element:

Private Function AddCustomer_onclick() As Boolean

' Run the Customers Command object.


MyDataEnvironment.Customers

' Append values from the DHTML Page object's elements


' to the command's underlying recordset.
With MyDataEnvironment.rsCustomers
.AddNew
!CustomerID = CustomerID.Value
!CompanyName = CompanyName.Value
!Address = Address.Value
!City = City.Value
!Region = Region.Value
!PostalCode = PostalCode.Value
!Country = Country.Value
.Update
.Close
End With

' Clear the elements.


CustomerID.Value = ""
CompanyName.Value = ""
Address.Value = ""
City.Value = ""
Region.Value = ""
PostalCode.Value = ""
Country.Value = ""

End Function

For More Information For more information on using ADO, see ADO, DAO and RDO in Visual Basic.

Load the HTML Page


To view the finished page in Internet Explorer, press F5 or click the Start button on the toolbar. You can also explicitly make a dynamic-link library and HTML page for the project by setting
properties on the Make tab of the Project Properties dialog box, then selecting Make .dll from the File menu.

For More Information For more information on testing your DHTML applications, see Testing Your DHTML Application in Chapter 2, "Developing DHTML Applications" in Building Internet
Applications in the Component Tools Guide.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateDataInputForm.asp (2 of 3) [11/17/2002 11:18:01 PM]


Welcome to the MSDN Library

Step by Step

This topic is part of a series that walks you through creating a simple DHTML application that interacts with data in an SQL Server database.

To See

Go to the next step Creating an HTML Page for Viewing and Updating Data

Start from the beginning Creating a DHTML Application that Interacts with SQL Server Data

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateDataInputForm.asp (3 of 3) [11/17/2002 11:18:01 PM]


Creating an HTML Page for Viewing and Updating Data

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server Data

Visual Basic Concepts

Creating an HTML Page for Viewing and Updating Data

See Also

To work with existing data in a SQL Server database, you can create an HTML page that lets you view and edit the data. You can use the DHTML Page designer to create a new HTML page or
modify an existing page. Then write code that uses ADO and the BindingsCollection object to handle data processing.

This topic shows how to create an HTML page to view and edit data in the Customers table you created and populated in the previous topic in this scenario. It shows how to use a data environment
Command object, ADO code, and the BindingsCollection object to directly update SQL Server data from the HTML page.

To create an HTML page for viewing and update data

1. Add labels and TextField elements to a new HTML page.

2. Modify the data environment Command object to allow data updating.

3. Add code to display records on the HTML page.

4. Add Button elements to navigate through records.

5. Load the HTML page.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in an SQL Server database. It begins with the topic Creating a DHTML
Application that Interacts with SQL Server Data.

Add Labels and TextField Elements to a New HTML Page


The first step in creating an HTML page for viewing and updating data is to open a new HTML page, by selecting Add DHTML Page from the Project menu.

You can use the DHTML Page designer to add labels and TextField elements to the HTML page. For example, to create an HTML page for viewing and updating data in the Customers table in the
Pubs sample database, follow the steps in the Creating a Data Entry HTML Page topic.

Modify the Data Environment Command Object to Allow Data


Updating
When you create a Command object using the Data Environment designer, the Command object by default allows you to read but not update the Command object's data source. To allow data
updating, you must change the Command object's CursorType, CursorLocation, and LockType properties.

For example, you can change the Customers Command object's CursorType, CursorLocation, and LockType properties to allow data in the Customers table to be updated directly from your HTML
page. In the Data Environment designer, select the Customers Command object and click the Properties button on the Data Environment toolbar. Click the Advanced tab, and then set the
CursorLocation property to Use server-side cursors, the CursorType property to Keyset, and the LockType property to Optimistic.

Add Code to Display Records on the HTML Page


Using the data environment, ADO, and the BindingCollection object, you can bind elements on an HTML page to SQL Server data when the page loads. You can then edit the data, and add code to
update the underlying recordset or navigate through the records. For example, you can use a BindingCollection object with an ADO Recordset object to bind the TextField elements on your HTML
Page to fields in the Customers table.

First, add a reference to the BindingCollection object's type library to your project. To add the reference, select References on the Project menu, then select Microsoft Data Binding Collection in the
References dialog box. Then declare a BindingCollection object variable in the HTML Page object's Declarations section:

Dim colBind As BindingCollection

To bind the elements to the table fields when the HTML page loads in your browser, add code to the DHTML Page object's Load event procedure. As you saw in the "Creating a Data Entry HTML
Page" topic, your data environment can provide the "middle tier" between the table and the HTML page.

Use the BindingCollection object to bind the elements on the HTML page to fields in the recordset:

Private Sub DHTMLPage_Load()

http://msdn.microsoft.com/library/en-us/vbcon98/.../vbconCreateSQLTableUsingDesigner.asp?frame=true (1 of 2) [11/17/2002 11:18:05 PM]


Creating an HTML Page for Viewing and Updating Data
' Create a BindingCollection object, then set its
' DataSource property to your data environment and its
' DataMember property to the Customers command object.
Set colBind = New BindingCollection
With colBind
Set .DataSource = MyDataEnvironment
.DataMember = "Customers"

' Bind the Value property of elements on the HTML page


' to fields in the Customers recordset.
.Add CustomerID, "Value", "CustomerID"
.Add CompanyName, "Value", "CompanyName"
.Add Address, "Value", "Address"
.Add City, "Value", "City"
.Add Region, "Value", "Region"
.Add PostalCode, "Value", "PostalCode"
.Add Country, "Value", "Country"
End With

End Sub

For More Information For more information see BindingCollection object in the Language Reference.

Add Button Elements to Navigate through Records


After you've established data binding between your data environment and the object on the HTML page, you can easily create Button elements for navigating through records by using the
recordset's MoveNext and MovePrevious methods. For example, to create a Next button for your HTML page, use the DHTML Page designer to add a Button element to the HTML page. Change its
id and Name properties to Next. Then add the following line to the Button element's Next_onclick event procedure:

MyDataEnvironment.rsCustomers.MoveNext

Similarly, you can create a Previous button by adding a Button element to the HTML page and change its id and Name properties to Previous. Then add the following code to the Button element's
Previous_onclick event procedure:

MyDataEnvironment.rsCustomers.MovePrevious

When you load the HTML page, Visual Basic displays the records in the Customers table and lets you move forward and backward through the recordset.

Load the HTML Page


To view the finished page in Internet Explorer, press the F5 key or click the Start button on the Standard toolbar. You can also explicitly make a dynamic-link library and HTML page for the project
by setting properties on the Make tab of the Project Properties dialog box, then selecting Make .dll from the File menu.

Step by Step

This topic is part of a series that walks you through creating a simple DHTML application that interacts with data in an SQL Server database.

To See

Go to the next step Creating an HTML Page that Runs a Stored Procedure

Start from the beginning Creating a DHTML Application that Interacts with SQL Server Data

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/.../vbconCreateSQLTableUsingDesigner.asp?frame=true (2 of 2) [11/17/2002 11:18:05 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server Data

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating an HTML Page for Viewing and Updating Data

See Also

Up One Level To work with existing data in a SQL Server database, you can create an HTML page that lets you view and edit the data. You can use the DHTML Page designer to create a new HTML page or
modify an existing page. Then write code that uses ADO and the BindingsCollection object to handle data processing.
Add a Table to an SQL Server Database
Create a Data Entry HTML Page This topic shows how to create an HTML page to view and edit data in the Customers table you created and populated in the previous topic in this scenario. It shows how to use a data
Create an HTML Page for Viewing and Updating Data environment Command object, ADO code, and the BindingsCollection object to directly update SQL Server data from the HTML page.

Create an HTML Page that Runs a Stored Procedure


To create an HTML page for viewing and update data

1. Add labels and TextField elements to a new HTML page.

2. Modify the data environment Command object to allow data updating.

3. Add code to display records on the HTML page.

4. Add Button elements to navigate through records.

5. Load the HTML page.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in an SQL Server database. It begins with the topic Creating a DHTML
Application that Interacts with SQL Server Data.

Add Labels and TextField Elements to a New HTML Page


The first step in creating an HTML page for viewing and updating data is to open a new HTML page, by selecting Add DHTML Page from the Project menu.

You can use the DHTML Page designer to add labels and TextField elements to the HTML page. For example, to create an HTML page for viewing and updating data in the Customers table in
the Pubs sample database, follow the steps in the Creating a Data Entry HTML Page topic.

Modify the Data Environment Command Object to Allow Data


Updating
When you create a Command object using the Data Environment designer, the Command object by default allows you to read but not update the Command object's data source. To allow data
updating, you must change the Command object's CursorType, CursorLocation, and LockType properties.

For example, you can change the Customers Command object's CursorType, CursorLocation, and LockType properties to allow data in the Customers table to be updated directly from your
HTML page. In the Data Environment designer, select the Customers Command object and click the Properties button on the Data Environment toolbar. Click the Advanced tab, and then set
the CursorLocation property to Use server-side cursors, the CursorType property to Keyset, and the LockType property to Optimistic.

Add Code to Display Records on the HTML Page

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateSQLTableUsingDesigner.asp (1 of 3) [11/17/2002 11:18:07 PM]


Welcome to the MSDN Library
Using the data environment, ADO, and the BindingCollection object, you can bind elements on an HTML page to SQL Server data when the page loads. You can then edit the data, and add
code to update the underlying recordset or navigate through the records. For example, you can use a BindingCollection object with an ADO Recordset object to bind the TextField elements on
your HTML Page to fields in the Customers table.

First, add a reference to the BindingCollection object's type library to your project. To add the reference, select References on the Project menu, then select Microsoft Data Binding Collection in
the References dialog box. Then declare a BindingCollection object variable in the HTML Page object's Declarations section:

Dim colBind As BindingCollection

To bind the elements to the table fields when the HTML page loads in your browser, add code to the DHTML Page object's Load event procedure. As you saw in the "Creating a Data Entry HTML
Page" topic, your data environment can provide the "middle tier" between the table and the HTML page.

Use the BindingCollection object to bind the elements on the HTML page to fields in the recordset:

Private Sub DHTMLPage_Load()

' Create a BindingCollection object, then set its


' DataSource property to your data environment and its
' DataMember property to the Customers command object.
Set colBind = New BindingCollection
With colBind
Set .DataSource = MyDataEnvironment
.DataMember = "Customers"

' Bind the Value property of elements on the HTML page


' to fields in the Customers recordset.
.Add CustomerID, "Value", "CustomerID"
.Add CompanyName, "Value", "CompanyName"
.Add Address, "Value", "Address"
.Add City, "Value", "City"
.Add Region, "Value", "Region"
.Add PostalCode, "Value", "PostalCode"
.Add Country, "Value", "Country"
End With

End Sub

For More Information For more information see BindingCollection object in the Language Reference.

Add Button Elements to Navigate through Records


After you've established data binding between your data environment and the object on the HTML page, you can easily create Button elements for navigating through records by using the
recordset's MoveNext and MovePrevious methods. For example, to create a Next button for your HTML page, use the DHTML Page designer to add a Button element to the HTML page. Change
its id and Name properties to Next. Then add the following line to the Button element's Next_onclick event procedure:

MyDataEnvironment.rsCustomers.MoveNext

Similarly, you can create a Previous button by adding a Button element to the HTML page and change its id and Name properties to Previous. Then add the following code to the Button
element's Previous_onclick event procedure:

MyDataEnvironment.rsCustomers.MovePrevious

When you load the HTML page, Visual Basic displays the records in the Customers table and lets you move forward and backward through the recordset.

Load the HTML Page


To view the finished page in Internet Explorer, press the F5 key or click the Start button on the Standard toolbar. You can also explicitly make a dynamic-link library and HTML page for the
project by setting properties on the Make tab of the Project Properties dialog box, then selecting Make .dll from the File menu.

Step by Step

This topic is part of a series that walks you through creating a simple DHTML application that interacts with data in an SQL Server database.

To See

Go to the next step Creating an HTML Page that Runs a Stored Procedure

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateSQLTableUsingDesigner.asp (2 of 3) [11/17/2002 11:18:07 PM]


Welcome to the MSDN Library
Start from the beginning Creating a DHTML Application that Interacts with SQL Server Data

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateSQLTableUsingDesigner.asp (3 of 3) [11/17/2002 11:18:07 PM]


Creating an HTML Page that Runs a Stored Procedure

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server Data

Visual Basic Concepts

Creating an HTML Page that Runs a Stored Procedure

See Also

You can increase the power and flexibility of your HTML applications by enabling them to run SQL Server stored procedures. You can create a stored procedure in the Data View window, then create
Command objects and elements that use the stored procedure to view or update data.

This topic shows how to create a stored procedure that returns customer address records by country from the Customers table created earlier in this scenario. It shows how to add a Select element to the
HTML page you created in the previous topic. The Select element uses the stored procedure to display address records based on the selected country.

To create an HTML page that runs a stored procedure

1. Add a stored procedure to the database.

2. Create a data environment Command object based on the stored procedure.

3. Add Labels and TextField Elements to a new HTML Page.

4. Add a Select element to the HTML page.

5. Add code to run the stored procedure and display the results.

6. Load the HTML page.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in an SQL Server database. It begins with the topic Creating a DHTML Application
that Interacts with SQL Server Data.

Add a Stored Procedure to the Database


You can add a stored procedure to the database by right-clicking the Stored Procedures folder in the Data View window and selecting the New Stored Procedure command. The Data View window displays
the New Stored Procedure window, where you enter the SQL Create Procedure statement that defines the stored procedure.

For example, you can add a spCustByCountry stored procedure to the Pubs database that accepts an input parameter, Country, and returns customer address information for the specified country. Enter
the following Create Procedure statement in the New Stored Procedure window:

CREATE PROCEDURE spCustByCountry @Country varchar(20)


AS
SELECT * FROM Customers
WHERE Country = @Country

When you save the stored procedure, it is added to the database.

For More Information For more information on using the Data View window to create a stored procedure, see Stored Procedures in the SQL Editor.

Create a Data Environment Command Object Based on the Stored


Procedure
In the "Create a Data Entry HTML Page" topic, you created a data environment Command object based on the Customers table in the Pubs sample database. You can also create a data environment
Command object based on a stored procedure.

For example, you can create a data environment Command object based on the spCustByCountry stored procedure. Follow the steps in the "Interacting with Data in a Microsoft Jet/Microsoft Access
Database" scenario, Chapter 5 of the Data Access Guide, to create the Command object, setting the following properties:

Property Setting

Command Name CustByCountry

Connection Connection1

Database Object Stored Procedure

Object Name dbo.spCustByCountry

Add Labels and TextField Elements to a New HTML Page

http://msdn.microsoft.com/library/en-us/vbcon98/.../vbconCreateNewQueryUsingDesigner.asp?frame=true (1 of 3) [11/17/2002 11:18:11 PM]


Creating an HTML Page that Runs a Stored Procedure
After you've created the command that will provide the data source for your HTML page, you can create the page. Select Add DHTML Page from the Project menu. As you saw in the previous topics in this
scenario, you can use the DHTML Page designer to add labels and TextField elements to the HTML page.

Add a Select Element to an HTML Page


You can use the DHTML Page designer to add a Select element to your HTML page. A Select element, similar to a combo box, lets you select an item from a list.

For example, to add a Select element called SelectCountry to the page you created in the previous topic, drag the element onto the page. Then set the element's Name and id properties to SelectCountry.

You can specify the list items to be displayed in the Select element by adding code to the HTML page's Load event procedure. For example, to display a list of countries included in the address information
from the Customers table, add the following code:

Private Sub DHTMLPage_Load()


' Declare Select element, connection, recordset, and string variables.
Dim selElement As HTMLSelectElement
Dim cnn As ADODB.Connection
Dim rsCountries As ADODB.Recordset
Dim strSQL As String

' Assign the list of countries from the Customers table


' to the recordset variable.
strSQL = "SELECT DISTINCT Country FROM Customers;"
Set cnn = New ADODB.Connection
cnn.Open MyDataEnvironment.Connection1
Set rsCountries = New ADODB.Recordset
rsCountries.Open strSQL, cnn1

' Fill the Select element's list with countries from the recordset, ' setting each list element's Text property. With rsCountries
Do While Not .EOF
Set selElement = DHTMLPage.Document.createElement("OPTION")
selElement.Text = !Country
SelectCountry.Options.Add selElement
.MoveNext
Loop
End With

End Sub

For More Information For more information on creating a Select element, see Working with Lists in the Page Designer in Building Internet Applications in the Component Tools Guide.

Add Code to Run the Stored Procedure and Display the Results
Using the data environment, ADO, and the BindingCollection object, you can easily add code to a Select element's onafterupdate event procedure to run a Command object that is based on a stored
procedure. You can then update the data displayed in an HTML page.

For example, you can display address records on your HTML page for customers from a country selected in the SelectCountry element. First, declare a BindingCollection object variable in the HTML Page
object's Declarations section:

Dim colBind As BindingCollection

Then add code to the element's onchange event procedure to run the cmdCustByCountry Command object using the value of the element as an input parameter:

Private Sub SelectCountry_onchange()

Dim rsResults As ADODB.Recordset


Dim intIndex As Integer

' Run the CustByCountry Command object using the value


' of the SelectCountry element as an input parameter.
intIndex = SelectCountry.selectedIndex
MyDataEnvironment.CustByCountry SelectCountry.Options(intIndex).Text

' Create a BindingCollection object, then set its


' DataSource property to your data environment and its
' DataMember property to the CustByCountry Command object.
Set colBind = New BindingCollection
With colBind
Set .DataSource = MyDataEnvironment
.DataMember = "CustByCountry"

' Bind the Value property of elements on the HTML page


' to fields in the CustByCountry recordset.
.Add CustomerID, "Value", "CustomerID"
.Add CompanyName, "Value", "CompanyName"
.Add Address, "Value", "Address"
.Add City, "Value", "City"
.Add Region, "Value", "Region"
.Add PostalCode, "Value", "PostalCode"
.Add Country, "Value", "Country"
End With

' Assign the recordset to the rsResults recordset variable. Set rsResults = MyDataEnvironment.rsCustByCountry ' Add HTML code to dynamically create a table on the
page
' showing each customer record.
DHTMLPage.Document.body.insertAdjacentHTML "BeforeEnd", "<DIV><HR SIZE=2></DIV>" With rsResults Do While Not .EOF DHTMLPage.Document.body.insertAdjacentHTML
"BeforeEnd", _ "<TABLE BORDER CELLSPACING=1 CELLPADDING=7 ><TR HEIGHT=17>" & _
"<TD WIDTH=70>" & rsResults!CustomerID & "</TD>" & _
"<TD WIDTH=200>" & rsResults!CompanyName & "</TD>" & _

http://msdn.microsoft.com/library/en-us/vbcon98/.../vbconCreateNewQueryUsingDesigner.asp?frame=true (2 of 3) [11/17/2002 11:18:11 PM]


Creating an HTML Page that Runs a Stored Procedure

"<TD WIDTH=300>" & rsResults!Address & "</TD>" & _


"<TD WIDTH=100>" & rsResults!City & "</TD>" & _
"<TD WIDTH=50>" & rsResults!Region & "</TD>" & _
"<TD WIDTH=50>" & rsResults!PostalCode & "</TD>" & _
"<TD WIDTH=50>" & rsResults!Country & "</TD></TR>" & _
"</TABLE>"
.MoveNext
Loop
.MoveFirst
.Close
End With

End Sub

Load the HTML Page


To view the finished page in Internet Explorer, press F5 or click the Start button on the Standard toolbar. You can also explicitly make a dynamic-link library and HTML page for the project by setting
properties on the Make tab of the Project Properties dialog box, then clicking Make .dll on the File menu.

Step by Step
This topic concludes a series that walks you through creating a simple DHTML application that interacts with data in an SQL Server database. To start from the beginning, see Creating a DHTML
Application that Interacts with SQL Server Data.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/.../vbconCreateNewQueryUsingDesigner.asp?frame=true (3 of 3) [11/17/2002 11:18:11 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server Data

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating an HTML Page that Runs a Stored Procedure

See Also

Up One Level You can increase the power and flexibility of your HTML applications by enabling them to run SQL Server stored procedures. You can create a stored procedure in the Data View window, then
create Command objects and elements that use the stored procedure to view or update data.
Add a Table to an SQL Server Database
Create a Data Entry HTML Page This topic shows how to create a stored procedure that returns customer address records by country from the Customers table created earlier in this scenario. It shows how to add a Select
Create an HTML Page for Viewing and Updating Data element to the HTML page you created in the previous topic. The Select element uses the stored procedure to display address records based on the selected country.

Create an HTML Page that Runs a Stored Procedure


To create an HTML page that runs a stored procedure

1. Add a stored procedure to the database.

2. Create a data environment Command object based on the stored procedure.

3. Add Labels and TextField Elements to a new HTML Page.

4. Add a Select element to the HTML page.

5. Add code to run the stored procedure and display the results.

6. Load the HTML page.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in an SQL Server database. It begins with the topic Creating a DHTML
Application that Interacts with SQL Server Data.

Add a Stored Procedure to the Database


You can add a stored procedure to the database by right-clicking the Stored Procedures folder in the Data View window and selecting the New Stored Procedure command. The Data View
window displays the New Stored Procedure window, where you enter the SQL Create Procedure statement that defines the stored procedure.

For example, you can add a spCustByCountry stored procedure to the Pubs database that accepts an input parameter, Country, and returns customer address information for the specified
country. Enter the following Create Procedure statement in the New Stored Procedure window:

CREATE PROCEDURE spCustByCountry @Country varchar(20)


AS
SELECT * FROM Customers
WHERE Country = @Country

When you save the stored procedure, it is added to the database.

For More Information For more information on using the Data View window to create a stored procedure, see Stored Procedures in the SQL Editor.

Create a Data Environment Command Object Based on the Stored


Procedure
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateNewQueryUsingDesigner.asp (1 of 3) [11/17/2002 11:18:13 PM]
Welcome to the MSDN Library
In the "Create a Data Entry HTML Page" topic, you created a data environment Command object based on the Customers table in the Pubs sample database. You can also create a data
environment Command object based on a stored procedure.

For example, you can create a data environment Command object based on the spCustByCountry stored procedure. Follow the steps in the "Interacting with Data in a Microsoft Jet/Microsoft
Access Database" scenario, Chapter 5 of the Data Access Guide, to create the Command object, setting the following properties:

Property Setting

Command Name CustByCountry

Connection Connection1

Database Object Stored Procedure

Object Name dbo.spCustByCountry

Add Labels and TextField Elements to a New HTML Page


After you've created the command that will provide the data source for your HTML page, you can create the page. Select Add DHTML Page from the Project menu. As you saw in the previous
topics in this scenario, you can use the DHTML Page designer to add labels and TextField elements to the HTML page.

Add a Select Element to an HTML Page


You can use the DHTML Page designer to add a Select element to your HTML page. A Select element, similar to a combo box, lets you select an item from a list.

For example, to add a Select element called SelectCountry to the page you created in the previous topic, drag the element onto the page. Then set the element's Name and id properties to
SelectCountry.

You can specify the list items to be displayed in the Select element by adding code to the HTML page's Load event procedure. For example, to display a list of countries included in the address
information from the Customers table, add the following code:

Private Sub DHTMLPage_Load()


' Declare Select element, connection, recordset, and string variables.
Dim selElement As HTMLSelectElement
Dim cnn As ADODB.Connection
Dim rsCountries As ADODB.Recordset
Dim strSQL As String

' Assign the list of countries from the Customers table


' to the recordset variable.
strSQL = "SELECT DISTINCT Country FROM Customers;"
Set cnn = New ADODB.Connection
cnn.Open MyDataEnvironment.Connection1
Set rsCountries = New ADODB.Recordset
rsCountries.Open strSQL, cnn1

' Fill the Select element's list with countries from the recordset, ' setting each list element's Text
property. With rsCountries
Do While Not .EOF
Set selElement = DHTMLPage.Document.createElement("OPTION")
selElement.Text = !Country
SelectCountry.Options.Add selElement
.MoveNext
Loop
End With

End Sub

For More Information For more information on creating a Select element, see Working with Lists in the Page Designer in Building Internet Applications in the Component Tools Guide.

Add Code to Run the Stored Procedure and Display the Results
Using the data environment, ADO, and the BindingCollection object, you can easily add code to a Select element's onafterupdate event procedure to run a Command object that is based on a
stored procedure. You can then update the data displayed in an HTML page.

For example, you can display address records on your HTML page for customers from a country selected in the SelectCountry element. First, declare a BindingCollection object variable in the
HTML Page object's Declarations section:

Dim colBind As BindingCollection

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateNewQueryUsingDesigner.asp (2 of 3) [11/17/2002 11:18:13 PM]


Welcome to the MSDN Library

Then add code to the element's onchange event procedure to run the cmdCustByCountry Command object using the value of the element as an input parameter:

Private Sub SelectCountry_onchange()

Dim rsResults As ADODB.Recordset


Dim intIndex As Integer

' Run the CustByCountry Command object using the value


' of the SelectCountry element as an input parameter.
intIndex = SelectCountry.selectedIndex
MyDataEnvironment.CustByCountry SelectCountry.Options(intIndex).Text

' Create a BindingCollection object, then set its


' DataSource property to your data environment and its
' DataMember property to the CustByCountry Command object.
Set colBind = New BindingCollection
With colBind
Set .DataSource = MyDataEnvironment
.DataMember = "CustByCountry"

' Bind the Value property of elements on the HTML page


' to fields in the CustByCountry recordset.
.Add CustomerID, "Value", "CustomerID"
.Add CompanyName, "Value", "CompanyName"
.Add Address, "Value", "Address"
.Add City, "Value", "City"
.Add Region, "Value", "Region"
.Add PostalCode, "Value", "PostalCode"
.Add Country, "Value", "Country"
End With

' Assign the recordset to the rsResults recordset variable. Set rsResults =
MyDataEnvironment.rsCustByCountry ' Add HTML code to dynamically create a table on the page
' showing each customer record.
DHTMLPage.Document.body.insertAdjacentHTML "BeforeEnd", "<DIV><HR SIZE=2></DIV>" With rsResults Do While
Not .EOF DHTMLPage.Document.body.insertAdjacentHTML "BeforeEnd", _ "<TABLE BORDER CELLSPACING=1
CELLPADDING=7 ><TR HEIGHT=17>" & _
"<TD WIDTH=70>" & rsResults!CustomerID & "</TD>" & _
"<TD WIDTH=200>" & rsResults!CompanyName & "</TD>" & _
"<TD WIDTH=300>" & rsResults!Address & "</TD>" & _
"<TD WIDTH=100>" & rsResults!City & "</TD>" & _
"<TD WIDTH=50>" & rsResults!Region & "</TD>" & _
"<TD WIDTH=50>" & rsResults!PostalCode & "</TD>" & _
"<TD WIDTH=50>" & rsResults!Country & "</TD></TR>" & _
"</TABLE>"
.MoveNext
Loop
.MoveFirst
.Close
End With

End Sub

Load the HTML Page


To view the finished page in Internet Explorer, press F5 or click the Start button on the Standard toolbar. You can also explicitly make a dynamic-link library and HTML page for the project by
setting properties on the Make tab of the Project Properties dialog box, then clicking Make .dll on the File menu.

Step by Step
This topic concludes a series that walks you through creating a simple DHTML application that interacts with data in an SQL Server database. To start from the beginning, see Creating a
DHTML Application that Interacts with SQL Server Data.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateNewQueryUsingDesigner.asp (3 of 3) [11/17/2002 11:18:13 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)

MSDN Library GO
Advanced Search Visual Basic Concepts

Interacting with Data in an ASCII Text File

See Also

Up One Level The data your application needs to interact with may not always be stored in a relational database. It may be stored in delimited or fixed-length fields in an ASCII text file. For example, your
application's data source may be data downloaded into a text file from a mainframe computer, a file converted from an unsupported database format or operating system, or an "ad hoc" data
Creating a Data-Aware Class that Reads Records from a Delimited Text File file created with a text editor.

Creating a Form that Lets You View and Update Data from a Data-Aware Class
Modifying the Form to Let You Add New Records By creating a data-aware class and using Microsoft ActiveX Data Objects (ADO), you can use Visual Basic to create applications that interact with data in an ASCII text file. Your application
can read data from a text file, update fields, add new records, and write data back to the text file as if the data were stored in a relational database.
Modifying the Class and Form to Write Records Back to the Delimited Text File
Topics

This series of topics shows you how to use a data-aware class and ADO to create a simple database application that interacts with data in a tab-delimited text file. It demonstrates:

● Creating a data-aware class that reads records from a delimited text file

● Creating a form that lets you view and update data from a data-aware class

● Modifying the form to let you add new records

● Modifying the class and form to write records back to the delimited text file

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconGetDataFromASCIIFile.asp [11/17/2002 11:18:23 PM]


Creating a Data-Aware Class that Reads Records from a Delimited Text File

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File

Visual Basic Concepts

Creating a Data-Aware Class that Reads Records from a Delimited Text File

See Also

By creating a data-aware class, you can read data from a delimited text file into an ADO recordset and use the features of ADO to manipulate the data. You can then use the class as a data source
in your application, binding controls on a form to fields in the recordset.

This topic shows how to create a data-aware class that reads data in a tab-delimited text file and provides methods for navigating through the data.

To create a data-aware class that reads data from a delimited text file

1. Create a class that acts as a data source.

2. Add code to read data from the text file into an ADO recordset.

3. Set the data source for the class.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. It begins with the topic Interacting with Data
in an ASCII Text File.

Create a Class that Acts as a Data Source


You can create a class that acts as a data source by inserting a class module in your project and specifying its data source behavior. First, insert a class module in your project by selecting Add
Class Module from the Project menu. Then set the Name and DataSourceBehavior properties for the class.

For example, to create a CustomerDataSource class that can act as a data source, set the following properties:

Property Setting

Name CustomerDataSource

DataSourceBehavior vbDataSource

For More Information Data-aware classes are covered in depth in Creating Data-Aware Classes in the Programmer's Guide.

Add Code to Read Data from the Text File into an ADO Recordset
By reading data from a text file into an ADO recordset, you can use the features of ADO to manipulate the data. First, add a reference to the ADO object library by selecting References on the
Project menu, then selecting Microsoft ActiveX Data Objects 2.0 Library in the References dialog box.

Then declare a Recordset object variable in the Declarations section for the class. For example, to declare a Recordset object variable for working with customer records from the Customers.txt
file, add the following to the Declarations section:

Public rsCustomers As ADODB.Recordset

By declaring the variable as a public variable, you can use the built-in methods of the Recordset object in applications that use the data-aware class.

Finally, add code to the Class_Initialize event procedure for the class to read data from the text file. For example, add the following code to the Class_Initialize event procedure for the
CustomerDataSource class to read data from the Customers.txt file into a recordset:

Private Sub Class_Initialize()

Dim fld As ADODB.Field


Dim strRow As String
Dim strField As String
Dim intPos As Integer

Set rsCustomers = New ADODB.Recordset

With rsCustomers
' Set CustomerID as the primary key.

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreateNewDataSource.asp?frame=true (1 of 2) [11/17/2002 11:18:26 PM]


Creating a Data-Aware Class that Reads Records from a Delimited Text File
.Fields.Append "CustomerID", adChar, 5, adFldRowID
.Fields.Append "CompanyName", adChar, 40, adFldUpdatable
.Fields.Append "ContactName", adChar, 30, adFldUpdatable
.Fields.Append "ContactTitle", adChar, 30, adFldUpdatable
.Fields.Append "Address", adChar, 60, adFldUpdatable
.Fields.Append "City", adChar, 15, adFldUpdatable
.Fields.Append "Region", adChar, 15, adFldMayBeNull
.Fields.Append "PostalCode", adChar, 10, adFldMayBeNull
.Fields.Append "Country", adChar, 15, adFldUpdatable
.Fields.Append "Phone", adChar, 24, adFldUpdatable
.Fields.Append "Fax", adChar, 24, adFldMayBeNull
' Use Keyset cursor type to allow updating records.
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With

Open "Customers.txt" For Input As #1

Do Until EOF(1)
Line Input #1, strRow
With rsCustomers
.AddNew
For Each fld In .Fields
' If a tab delimiter is found, field text is to the
' left of the delimiter.
If InStr(strRow, Chr(9)) <> 0 Then
' Move position to tab delimiter.
intPos = InStr(strRow, Chr(9))
' Assign field text to strField variable.
strField = Left(strRow, intPos - 1)
Else
' If a tab delimiter isn't found, field text is the
' last field in the row.
strField = strRow
End If

' Strip off quotation marks.


If Left(strField, 1) = Chr(34) Then
strField = Left(strField, Len(strField) - 1)
strField = Right(strField, Len(strField) - 1)
End If

fld.Value = strField

' Strip off field value text from text row.


strRow = Right(strRow, Len(strRow) - intPos)
intPos = 0

Next
.Update
.MoveFirst
End With
Loop
Close

End Sub

Set the Data Source for the Class


When you specify a class as a data source by setting its DataSourceBehavior to vbDataSource, Visual Basic automatically adds a GetDataMember event to the class. The Class_GetDataMember
event procedure is where you set the data source for the class by assigning it to the Data object for the class.

For example, to set the rsCustomers recordset as the data source for the CustomerDataSource class, add the following to the Class_GetDataMember event procedure:

Private Sub Class_GetDataMember(DataMember As String, Data As Object) Set Data = rsCustomersEnd Sub

For More Information For a discussion of data sources, see Creating a Data Source in the Programmer's Guide.

Step by Step

This topic is part of a series that walks you through using a data-aware class and ADO to create a simple database application that interacts with data in a tab-delimited text file.

To See

Go to the next step Creating a Form that Lets You View and Update Data from a Data-Aware Class

Start from the beginning Interacting with Data in an ASCII Text File

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreateNewDataSource.asp?frame=true (2 of 2) [11/17/2002 11:18:26 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating a Data-Aware Class that Reads Records from a Delimited Text File

See Also

Up One Level By creating a data-aware class, you can read data from a delimited text file into an ADO recordset and use the features of ADO to manipulate the data. You can then use the class as a data
source in your application, binding controls on a form to fields in the recordset.
Creating a Data-Aware Class that Reads Records from a Delimited Text File
Creating a Form that Lets You View and Update Data from a Data-Aware Class This topic shows how to create a data-aware class that reads data in a tab-delimited text file and provides methods for navigating through the data.
Modifying the Form to Let You Add New Records
Modifying the Class and Form to Write Records Back to the Delimited Text File To create a data-aware class that reads data from a delimited text file

1. Create a class that acts as a data source.

2. Add code to read data from the text file into an ADO recordset.

3. Set the data source for the class.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. It begins with the topic Interacting with
Data in an ASCII Text File.

Create a Class that Acts as a Data Source


You can create a class that acts as a data source by inserting a class module in your project and specifying its data source behavior. First, insert a class module in your project by selecting
Add Class Module from the Project menu. Then set the Name and DataSourceBehavior properties for the class.

For example, to create a CustomerDataSource class that can act as a data source, set the following properties:

Property Setting

Name CustomerDataSource

DataSourceBehavior vbDataSource

For More Information Data-aware classes are covered in depth in Creating Data-Aware Classes in the Programmer's Guide.

Add Code to Read Data from the Text File into an ADO Recordset
By reading data from a text file into an ADO recordset, you can use the features of ADO to manipulate the data. First, add a reference to the ADO object library by selecting References on the
Project menu, then selecting Microsoft ActiveX Data Objects 2.0 Library in the References dialog box.

Then declare a Recordset object variable in the Declarations section for the class. For example, to declare a Recordset object variable for working with customer records from the
Customers.txt file, add the following to the Declarations section:

Public rsCustomers As ADODB.Recordset

By declaring the variable as a public variable, you can use the built-in methods of the Recordset object in applications that use the data-aware class.

Finally, add code to the Class_Initialize event procedure for the class to read data from the text file. For example, add the following code to the Class_Initialize event procedure for the
CustomerDataSource class to read data from the Customers.txt file into a recordset:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateNewDataSource.asp (1 of 3) [11/17/2002 11:18:28 PM]


Welcome to the MSDN Library
Private Sub Class_Initialize()

Dim fld As ADODB.Field


Dim strRow As String
Dim strField As String
Dim intPos As Integer

Set rsCustomers = New ADODB.Recordset

With rsCustomers
' Set CustomerID as the primary key.
.Fields.Append "CustomerID", adChar, 5, adFldRowID
.Fields.Append "CompanyName", adChar, 40, adFldUpdatable
.Fields.Append "ContactName", adChar, 30, adFldUpdatable
.Fields.Append "ContactTitle", adChar, 30, adFldUpdatable
.Fields.Append "Address", adChar, 60, adFldUpdatable
.Fields.Append "City", adChar, 15, adFldUpdatable
.Fields.Append "Region", adChar, 15, adFldMayBeNull
.Fields.Append "PostalCode", adChar, 10, adFldMayBeNull
.Fields.Append "Country", adChar, 15, adFldUpdatable
.Fields.Append "Phone", adChar, 24, adFldUpdatable
.Fields.Append "Fax", adChar, 24, adFldMayBeNull
' Use Keyset cursor type to allow updating records.
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With

Open "Customers.txt" For Input As #1

Do Until EOF(1)
Line Input #1, strRow
With rsCustomers
.AddNew
For Each fld In .Fields
' If a tab delimiter is found, field text is to the
' left of the delimiter.
If InStr(strRow, Chr(9)) <> 0 Then
' Move position to tab delimiter.
intPos = InStr(strRow, Chr(9))
' Assign field text to strField variable.
strField = Left(strRow, intPos - 1)
Else
' If a tab delimiter isn't found, field text is the
' last field in the row.
strField = strRow
End If

' Strip off quotation marks.


If Left(strField, 1) = Chr(34) Then
strField = Left(strField, Len(strField) - 1)
strField = Right(strField, Len(strField) - 1)
End If

fld.Value = strField

' Strip off field value text from text row.


strRow = Right(strRow, Len(strRow) - intPos)
intPos = 0

Next
.Update
.MoveFirst
End With
Loop
Close

End Sub

Set the Data Source for the Class


When you specify a class as a data source by setting its DataSourceBehavior to vbDataSource, Visual Basic automatically adds a GetDataMember event to the class. The
Class_GetDataMember event procedure is where you set the data source for the class by assigning it to the Data object for the class.

For example, to set the rsCustomers recordset as the data source for the CustomerDataSource class, add the following to the Class_GetDataMember event procedure:

Private Sub Class_GetDataMember(DataMember As String, Data As Object) Set Data = rsCustomersEnd Sub

For More Information For a discussion of data sources, see Creating a Data Source in the Programmer's Guide.

Step by Step

This topic is part of a series that walks you through using a data-aware class and ADO to create a simple database application that interacts with data in a tab-delimited text file.

To See

Go to the next step Creating a Form that Lets You View and Update Data from a Data-Aware Class

Start from the beginning Interacting with Data in an ASCII Text File

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateNewDataSource.asp (2 of 3) [11/17/2002 11:18:28 PM]


Welcome to the MSDN Library
Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateNewDataSource.asp (3 of 3) [11/17/2002 11:18:28 PM]


Creating a Form that Lets You View and Update Data from a Data-Aware Class

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File

Visual Basic Concepts

Creating a Form that Lets You View and Update Data from a Data-Aware Class

See Also

Once you've created a class that can act as a data source, you can easily create applications that let you view and update records from the data source. You can use ActiveX Data Objects (ADO)
and the BindingsCollection object to bind the data source to controls on the form, and add command buttons to navigate through records.

This topic shows how to create a form that lets you view and edit customer address records from the data-aware class you created in the previous topic.

To create a form that lets you view and update data from a data-aware class

1. Add text box and label controls to a form.

2. Add code to bind the text box controls to the data source.

3. Add command button controls to navigate through records.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. It begins with the topic Interacting with Data
in an ASCII Text File.

Add Text Box and Label Controls to a Form


The first step in viewing and updating data from a data-aware class is to create an interface for interacting with records from the data source. The easiest way to create an interface is to open a
new Standard EXE project, then add TextBox and Label controls to a form.

For example, you can create an interface for viewing customer address information from the Customers.txt file. First, add a "Customer ID:" label to the form, then add a text box control next to
the label and set its Name property to txtCustomerID. Repeat the same process for CompanyName, Address, City, Region, PostalCode, and Country controls.

Add Code to Bind the Text Box Controls to the Data Source
Using a data-aware class, ActiveX Data Objects (ADO), and the BindingCollection object, you can bind controls to a data source when the page loads. You can then edit the data and add code to
navigate through the records. For example, you can use an instance of your data-aware class and the BindingCollection object to bind the text box controls on your form to fields from the
Customers.txt file.

First, add a reference to the BindingCollection object's type library to your project. To add the reference, select References on the Project menu, then select Microsoft Data Binding Collection in the
References dialog box.

Then declare variables for the data-aware class and a BindingCollection object in your form's Declarations section:

Private objDataSource As CustomerDataSource


Private colBind As BindingCollection

To bind the text box controls to fields from the Customers.txt file when the form loads, add code to the form's Load event procedure. An instance of the CustomerDataSource class reads records
from the text file into an ADO recordset, and the BindingCollection object binds the text box controls to fields in the recordset:

Private Sub Form_Load()

Set objDataSource = New CustomerDataSource


Set colBind = New BindingCollection

Set colBind.DataSource = objDataSource


colBind.Add txtCustomerID, "Text", "CustomerID"
colBind.Add txtCompanyName, "Text", "CompanyName"
colBind.Add txtAddress, "Text", "Address"
colBind.Add txtCity, "Text", "City"
colBind.Add txtRegion, "Text", "Region"
colBind.Add txtPostalCode, "Text", "PostalCode"
colBind.Add txtCountry, "Text", "Country"

End Sub

Add Command Button Controls to Navigate through Records

http://msdn.microsoft.com/library/en-us/vbcon98/...vbconCreateConnectionToDataSource.asp?frame=true (1 of 2) [11/17/2002 11:18:32 PM]


Creating a Form that Lets You View and Update Data from a Data-Aware Class

By binding controls on your form to a public recordset in your data-aware class, you can easily create Next and Previous buttons that let you navigate through records. Each command button
requires a single line of code.

For example, to create a Next button for the form that displays customer records, add a command button to the form and change its Caption and Name properties to Next. Then add the following
line to the command button's Next_Click event procedure:

objDataSource.rsCustomers.MoveNext

The code uses the MoveNext method of the rsCustomers recordset that serves as the data source for the form's controls. It refers to the recordset as a property of the object variable that
represents an instance of the CustomerDataSource class.

Similarly, you can create Previous, First, and Last buttons by adding command buttons to the form and changing their Caption and Name properties to Previous, First, and Last, respectively. Then
add code to the Click event procedure for each command button that invokes the MovePrevious, MoveFirst, and MoveLast methods.

When you run the form, Visual Basic lets you view and update records from the Customers.txt file and lets you navigate through the recordset.

Step by Step

This topic is part of a series that walks you through using a data-aware class and ADO to create a simple database application that interacts with data in a tab-delimited text file.

To See

Go to the next step Modifying the Form to Let You Add New Records

Start from the beginning Interacting with Data in an ASCII Text File

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/...vbconCreateConnectionToDataSource.asp?frame=true (2 of 2) [11/17/2002 11:18:32 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating a Form that Lets You View and Update Data from a Data-Aware Class

See Also

Up One Level Once you've created a class that can act as a data source, you can easily create applications that let you view and update records from the data source. You can use ActiveX Data Objects
(ADO) and the BindingsCollection object to bind the data source to controls on the form, and add command buttons to navigate through records.
Creating a Data-Aware Class that Reads Records from a Delimited Text File
Creating a Form that Lets You View and Update Data from a Data-Aware Class This topic shows how to create a form that lets you view and edit customer address records from the data-aware class you created in the previous topic.
Modifying the Form to Let You Add New Records
Modifying the Class and Form to Write Records Back to the Delimited Text File To create a form that lets you view and update data from a data-aware class

1. Add text box and label controls to a form.

2. Add code to bind the text box controls to the data source.

3. Add command button controls to navigate through records.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. It begins with the topic Interacting with
Data in an ASCII Text File.

Add Text Box and Label Controls to a Form


The first step in viewing and updating data from a data-aware class is to create an interface for interacting with records from the data source. The easiest way to create an interface is to open
a new Standard EXE project, then add TextBox and Label controls to a form.

For example, you can create an interface for viewing customer address information from the Customers.txt file. First, add a "Customer ID:" label to the form, then add a text box control next
to the label and set its Name property to txtCustomerID. Repeat the same process for CompanyName, Address, City, Region, PostalCode, and Country controls.

Add Code to Bind the Text Box Controls to the Data Source
Using a data-aware class, ActiveX Data Objects (ADO), and the BindingCollection object, you can bind controls to a data source when the page loads. You can then edit the data and add code
to navigate through the records. For example, you can use an instance of your data-aware class and the BindingCollection object to bind the text box controls on your form to fields from the
Customers.txt file.

First, add a reference to the BindingCollection object's type library to your project. To add the reference, select References on the Project menu, then select Microsoft Data Binding Collection
in the References dialog box.

Then declare variables for the data-aware class and a BindingCollection object in your form's Declarations section:

Private objDataSource As CustomerDataSource


Private colBind As BindingCollection

To bind the text box controls to fields from the Customers.txt file when the form loads, add code to the form's Load event procedure. An instance of the CustomerDataSource class reads
records from the text file into an ADO recordset, and the BindingCollection object binds the text box controls to fields in the recordset:

Private Sub Form_Load()

Set objDataSource = New CustomerDataSource


Set colBind = New BindingCollection

Set colBind.DataSource = objDataSource


colBind.Add txtCustomerID, "Text", "CustomerID"
colBind.Add txtCompanyName, "Text", "CompanyName"
colBind.Add txtAddress, "Text", "Address"
colBind.Add txtCity, "Text", "City"
colBind.Add txtRegion, "Text", "Region"

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateConnectionToDataSource.asp (1 of 2) [11/17/2002 11:18:34 PM]


Welcome to the MSDN Library
colBind.Add txtPostalCode, "Text", "PostalCode"
colBind.Add txtCountry, "Text", "Country"

End Sub

Add Command Button Controls to Navigate through Records


By binding controls on your form to a public recordset in your data-aware class, you can easily create Next and Previous buttons that let you navigate through records. Each command button
requires a single line of code.

For example, to create a Next button for the form that displays customer records, add a command button to the form and change its Caption and Name properties to Next. Then add the
following line to the command button's Next_Click event procedure:

objDataSource.rsCustomers.MoveNext

The code uses the MoveNext method of the rsCustomers recordset that serves as the data source for the form's controls. It refers to the recordset as a property of the object variable that
represents an instance of the CustomerDataSource class.

Similarly, you can create Previous, First, and Last buttons by adding command buttons to the form and changing their Caption and Name properties to Previous, First, and Last, respectively.
Then add code to the Click event procedure for each command button that invokes the MovePrevious, MoveFirst, and MoveLast methods.

When you run the form, Visual Basic lets you view and update records from the Customers.txt file and lets you navigate through the recordset.

Step by Step

This topic is part of a series that walks you through using a data-aware class and ADO to create a simple database application that interacts with data in a tab-delimited text file.

To See

Go to the next step Modifying the Form to Let You Add New Records

Start from the beginning Interacting with Data in an ASCII Text File

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreateConnectionToDataSource.asp (2 of 2) [11/17/2002 11:18:34 PM]


Modifying the Form to Let You Add New Records

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File

Visual Basic Concepts

Modifying the Form to Let You Add New Records

See Also

In addition to viewing and updating existing records, you may want to add new records to your data source. You can modify your form so that it can serve as a data entry form by creating
command buttons that use ActiveX Data Objects (ADO) and the BindingsCollection object to clear the display of data, manage the data binding of controls, and add a new record to the underlying
recordset.

This topic shows how to modify the form you created in the previous topic so that it also serves as a data entry form for adding new customer records.

To modify the form to let you add new records

1. Create command buttons for allowing data entry, adding new customer records, and returning to viewing data.

2. Add code to enable data entry.

3. Add code to enable saving the data you enter as a new record.

4. Add code to enable returning the form to viewing data.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. It begins with the topic Interacting with Data
in an ASCII Text File.

Create Command Buttons for Allowing Data Entry, Adding New


Customer Records, and Returning to Viewing Data
The first step in modifying the form is to create the interface for the tasks that you want to accomplish. For example, to allow data entry on the customer address form you created in the previous
topic, you could add the following:

● A DataEntry command button to clear the existing data displayed on the form and disable data binding.

● An AddCustomer command button to add new data entered on the form as a new record in the underlying recordset.

● A ViewData command button to re-enable data binding, returning the form to its original state.

First, add a command button to the form and change its Caption and Name properties to DataEntry. Add a second command button to the form and change its Caption and Name properties to
AddCustomer. Then add a third command button to the form and change its Caption and Name properties to ViewData.

Because the AddCustomer and ViewData command buttons should only be displayed when the form is being used for data entry, set the Visible property for these controls to False.

Add Code to Enable Data Entry


You can make a data-bound form also serve as a data entry form by disabling data binding and clearing the existing data displayed on the form. You may also want to show hidden command
button controls that apply only to adding new records, and hide command button controls that apply only to viewing existing records.

For example, to enable the DataEntry command button on the customer address form, add the following code to the DataEntry_Click event procedure:

Private Sub DataEntry_Click()


' Disable data binding.
Set colBind = Nothing

' Clear the text box controls.


Me.txtCustomerID = ""
Me.txtCompanyName = ""
Me.txtAddress = ""
Me.txtCity = ""
Me.txtRegion = ""
Me.txtPostalCode = ""
Me.txtCountry = ""

' Hide the command buttons used for viewing


' existing data.
Me.Next.Visible = False
Me.Previous.Visible = False
Me.First.Visible = False
Me.Last.Visible = False
Me.DataEntry.Visible = False

' Show the command buttons used for entering new data.
Me.AddCustomer.Visible = True

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconBindGridControlToSource.asp?frame=true (1 of 3) [11/17/2002 11:18:42 PM]


Modifying the Form to Let You Add New Records
Me.ViewData.Visible = True

End Sub

Add Code to Enable Saving the Data You Enter as a New Record
After you've entered record data in a data entry form, you can use ADO to add the record to a recordset. For example, to enable the AddCustomer command button on the customer address form,
add the following code to the AddCustomer_Click event procedure:

Private Sub AddCustomer_Click()

' Add the record to the rsCustomers recordset


' in your data-aware class.
With objDataSource.rsCustomers
.AddNew
!CustomerID = Me.txtCustomerID.Text
!CompanyName = Me.txtCompanyName.Text
!Address = Me.txtAddress.Text
!City = Me.txtCity.Text
!Region = Me.txtRegion.Text
!PostalCode = Me.txtPostalCode.Text
!Country = Me.txtCountry.Text
.Update

End With

' Clear the controls for additional data entry,


' if desired.
Me.txtCustomerID = ""
Me.txtCompanyName = ""
Me.txtAddress = ""
Me.txtCity = ""
Me.txtRegion = ""
Me.txtPostalCode = ""
Me.txtCountry = ""

End Sub

Add Code to Enable Returning the Form to Viewing Data


When you've finished using your form as a data entry form, you can return it to its original use for viewing and editing existing records by re-enabling data binding. Any new records you've
entered will now be displayed when you move through records on the form. You can also hide command button controls that apply only to adding new records, and show hidden command button
controls that apply to viewing existing records.

For example, to enable the ViewData command button on the customer address form, add the following code to the ViewData_Click event procedure:

Private Sub ViewData_Click()

' Bind text box controls to the data source


' of your data-aware class.
Set colBind = New BindingCollection

Set colBind.DataSource = objDataSource


colBind.Add txtCustomerID, "Text", "CustomerID"
colBind.Add txtCompanyName, "Text", "CompanyName"
colBind.Add txtAddress, "Text", "Address"
colBind.Add txtCity, "Text", "City"
colBind.Add txtRegion, "Text", "Region"
colBind.Add txtPostalCode, "Text", "PostalCode"
colBind.Add txtCountry, "Text", "Country"

' Show the command buttons used for viewing


' existing data.
Me.Next.Visible = True
Me.Previous.Visible = True
Me.First.Visible = True
Me.Last.Visible = True
Me.DataEntry.Visible = True

' Hide the command buttons used for entering new data.
Me.AddCustomer.Visible = False
Me.ViewData.Visible = False

End Sub

For More Information To read about the BindingCollection object, see Creating Data-Aware Classes in "Programming with Objects" in the Programmer's Guide.

Step by Step

This topic is part of a series that walks you through using a data-aware class and ADO to create a simple database application that interacts with data in a tab-delimited text file.

To See

Go to the next step Modifying the Class and Form to Write Records Back to the Delimited Text File

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconBindGridControlToSource.asp?frame=true (2 of 3) [11/17/2002 11:18:42 PM]


Modifying the Form to Let You Add New Records

Start from the beginning Interacting with Data in an ASCII Text File

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconBindGridControlToSource.asp?frame=true (3 of 3) [11/17/2002 11:18:42 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File

MSDN Library GO
Advanced Search Visual Basic Concepts

Modifying the Form to Let You Add New Records

See Also

Up One Level In addition to viewing and updating existing records, you may want to add new records to your data source. You can modify your form so that it can serve as a data entry form by creating
command buttons that use ActiveX Data Objects (ADO) and the BindingsCollection object to clear the display of data, manage the data binding of controls, and add a new record to the
Creating a Data-Aware Class that Reads Records from a Delimited Text File underlying recordset.

Creating a Form that Lets You View and Update Data from a Data-Aware Class
Modifying the Form to Let You Add New Records This topic shows how to modify the form you created in the previous topic so that it also serves as a data entry form for adding new customer records.

Modifying the Class and Form to Write Records Back to the Delimited Text File
To modify the form to let you add new records

1. Create command buttons for allowing data entry, adding new customer records, and returning to viewing data.

2. Add code to enable data entry.

3. Add code to enable saving the data you enter as a new record.

4. Add code to enable returning the form to viewing data.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. It begins with the topic Interacting with
Data in an ASCII Text File.

Create Command Buttons for Allowing Data Entry, Adding New


Customer Records, and Returning to Viewing Data
The first step in modifying the form is to create the interface for the tasks that you want to accomplish. For example, to allow data entry on the customer address form you created in the
previous topic, you could add the following:

● A DataEntry command button to clear the existing data displayed on the form and disable data binding.

● An AddCustomer command button to add new data entered on the form as a new record in the underlying recordset.

● A ViewData command button to re-enable data binding, returning the form to its original state.

First, add a command button to the form and change its Caption and Name properties to DataEntry. Add a second command button to the form and change its Caption and Name properties
to AddCustomer. Then add a third command button to the form and change its Caption and Name properties to ViewData.

Because the AddCustomer and ViewData command buttons should only be displayed when the form is being used for data entry, set the Visible property for these controls to False.

Add Code to Enable Data Entry


You can make a data-bound form also serve as a data entry form by disabling data binding and clearing the existing data displayed on the form. You may also want to show hidden command
button controls that apply only to adding new records, and hide command button controls that apply only to viewing existing records.

For example, to enable the DataEntry command button on the customer address form, add the following code to the DataEntry_Click event procedure:

Private Sub DataEntry_Click()


' Disable data binding.
Set colBind = Nothing

' Clear the text box controls.


Me.txtCustomerID = ""
Me.txtCompanyName = ""
Me.txtAddress = ""
Me.txtCity = ""
Me.txtRegion = ""
Me.txtPostalCode = ""

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconBindGridControlToSource.asp (1 of 3) [11/17/2002 11:18:44 PM]


Welcome to the MSDN Library
Me.txtCountry = ""

' Hide the command buttons used for viewing


' existing data.
Me.Next.Visible = False
Me.Previous.Visible = False
Me.First.Visible = False
Me.Last.Visible = False
Me.DataEntry.Visible = False

' Show the command buttons used for entering new data.
Me.AddCustomer.Visible = True
Me.ViewData.Visible = True

End Sub

Add Code to Enable Saving the Data You Enter as a New Record
After you've entered record data in a data entry form, you can use ADO to add the record to a recordset. For example, to enable the AddCustomer command button on the customer address
form, add the following code to the AddCustomer_Click event procedure:

Private Sub AddCustomer_Click()

' Add the record to the rsCustomers recordset


' in your data-aware class.
With objDataSource.rsCustomers
.AddNew
!CustomerID = Me.txtCustomerID.Text
!CompanyName = Me.txtCompanyName.Text
!Address = Me.txtAddress.Text
!City = Me.txtCity.Text
!Region = Me.txtRegion.Text
!PostalCode = Me.txtPostalCode.Text
!Country = Me.txtCountry.Text
.Update

End With

' Clear the controls for additional data entry,


' if desired.
Me.txtCustomerID = ""
Me.txtCompanyName = ""
Me.txtAddress = ""
Me.txtCity = ""
Me.txtRegion = ""
Me.txtPostalCode = ""
Me.txtCountry = ""

End Sub

Add Code to Enable Returning the Form to Viewing Data


When you've finished using your form as a data entry form, you can return it to its original use for viewing and editing existing records by re-enabling data binding. Any new records you've
entered will now be displayed when you move through records on the form. You can also hide command button controls that apply only to adding new records, and show hidden command
button controls that apply to viewing existing records.

For example, to enable the ViewData command button on the customer address form, add the following code to the ViewData_Click event procedure:

Private Sub ViewData_Click()

' Bind text box controls to the data source


' of your data-aware class.
Set colBind = New BindingCollection

Set colBind.DataSource = objDataSource


colBind.Add txtCustomerID, "Text", "CustomerID"
colBind.Add txtCompanyName, "Text", "CompanyName"
colBind.Add txtAddress, "Text", "Address"
colBind.Add txtCity, "Text", "City"
colBind.Add txtRegion, "Text", "Region"
colBind.Add txtPostalCode, "Text", "PostalCode"
colBind.Add txtCountry, "Text", "Country"

' Show the command buttons used for viewing


' existing data.
Me.Next.Visible = True
Me.Previous.Visible = True
Me.First.Visible = True
Me.Last.Visible = True
Me.DataEntry.Visible = True

' Hide the command buttons used for entering new data.
Me.AddCustomer.Visible = False
Me.ViewData.Visible = False

End Sub

For More Information To read about the BindingCollection object, see Creating Data-Aware Classes in "Programming with Objects" in the Programmer's Guide.

Step by Step

This topic is part of a series that walks you through using a data-aware class and ADO to create a simple database application that interacts with data in a tab-delimited text file.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconBindGridControlToSource.asp (2 of 3) [11/17/2002 11:18:44 PM]


Welcome to the MSDN Library
To See

Go to the next step Modifying the Class and Form to Write Records Back to the Delimited Text File

Start from the beginning Interacting with Data in an ASCII Text File

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconBindGridControlToSource.asp (3 of 3) [11/17/2002 11:18:44 PM]


Modifying the Class and Form to Write Records Back to the Delimited Text File

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File

Visual Basic Concepts

Modifying the Class and Form to Write Records Back to the Delimited Text File

See Also

After you've updated records or added new records, you can write the changes back to the delimited text file that serves as the data source for your data-aware class. You can add a public method
to the class that writes records to a file, then invoke the method in your applications.

This topic shows how to modify the CustomerDataSource class to provide a public method to write records back to the Customers.txt file, and how to invoke the method on your customer address
form.

To modify the class and form to write all records back to the delimited text file

1. Create a public method in the class that writes records to a file.

2. Create a command button on your form that writes records to a file.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. It begins with the topic Interacting with Data
in an ASCII Text File.

Create a Public Method in the Class that Writes Records to a File


By adding Sub procedures to your class, you can provide public methods to applications that use your class as a data source. For example, you can create a public method in your
CustomerDataSource class that writes current records from the rsCustomers recordset to the Customers.txt delimited text file. The text file will then include any changes or additions you've made
to the recordset.

To create a public WriteToFile method, add the following code to the CustomerDataSource class:

Public Sub WriteToFile()

Dim fld As ADODB.Field


Dim strRow As String
Dim strField As String

Open "Customers.txt" For Output As #1

With rsCustomers

.MoveFirst
Do While Not .EOF
For Each fld In .Fields
' If a field has a value, add quotation marks.
If Len(fld.Value) > 0 Then
strField = Chr(34) & fld.Value & Chr(34)
Else
strField = ""
End If
' Add the field value and a tab delimeter
' to the output string.
strRow = strRow & strField & Chr(9)
Next
' Strip off the end tab character.
strRow = Left(strRow, Len(strRow) - 1)
' Print the output string.
Print #1, strRow
strRow = ""
.MoveNext
Loop
End With
Close

End Sub

Create a Command Button on Your Form that Writes Records to a


File
Once you've created a public method in your data-aware class, you can use it in any application that requires the same functionality. For example, by creating a public method for writing records
to a delimited text file, you can easily create a WriteToFile button on your customer address form. The command button requires a single line of code.

To create a WriteToFile button, add a command button to the form and change its Caption and Name properties to WriteToFile. Then add the following line to the command button's
WriteToFile_Click event procedure:

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconFormatData.asp?frame=true (1 of 2) [11/17/2002 11:18:50 PM]


Modifying the Class and Form to Write Records Back to the Delimited Text File

objDataSource.WriteToFile

The code uses the WriteToFile method you created for the CustomerDataSource class.

You may want to hide the WriteToFile button while users enter data on the form. To hide the command button during data entry, add the following code to the DataEntry_Click event procedure:

Me.WriteToFile.Visible = False

And if you hide the WriteToFile button while users enter data, make it visible again while users view data. To do so, add the following code to the ViewData_Click event procedure:

Me.WriteToFile.Visible = True

Step by Step

This topic concludes a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. To start from the beginning, see Interacting with
Data in an ASCII Text File.

For More Information For information on data sources, see Creating Data Sources in the Component Tools Guide.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconFormatData.asp?frame=true (2 of 2) [11/17/2002 11:18:50 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File

MSDN Library GO
Advanced Search Visual Basic Concepts

Modifying the Class and Form to Write Records Back to the Delimited Text File

See Also

Up One Level After you've updated records or added new records, you can write the changes back to the delimited text file that serves as the data source for your data-aware class. You can add a public
method to the class that writes records to a file, then invoke the method in your applications.
Creating a Data-Aware Class that Reads Records from a Delimited Text File
Creating a Form that Lets You View and Update Data from a Data-Aware Class This topic shows how to modify the CustomerDataSource class to provide a public method to write records back to the Customers.txt file, and how to invoke the method on your customer
Modifying the Form to Let You Add New Records address form.

Modifying the Class and Form to Write Records Back to the Delimited Text File
To modify the class and form to write all records back to the delimited text file

1. Create a public method in the class that writes records to a file.

2. Create a command button on your form that writes records to a file.

Note This topic is part of a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. It begins with the topic Interacting with
Data in an ASCII Text File.

Create a Public Method in the Class that Writes Records to a File


By adding Sub procedures to your class, you can provide public methods to applications that use your class as a data source. For example, you can create a public method in your
CustomerDataSource class that writes current records from the rsCustomers recordset to the Customers.txt delimited text file. The text file will then include any changes or additions you've
made to the recordset.

To create a public WriteToFile method, add the following code to the CustomerDataSource class:

Public Sub WriteToFile()

Dim fld As ADODB.Field


Dim strRow As String
Dim strField As String

Open "Customers.txt" For Output As #1

With rsCustomers

.MoveFirst
Do While Not .EOF
For Each fld In .Fields
' If a field has a value, add quotation marks.
If Len(fld.Value) > 0 Then
strField = Chr(34) & fld.Value & Chr(34)
Else
strField = ""
End If
' Add the field value and a tab delimeter
' to the output string.
strRow = strRow & strField & Chr(9)
Next
' Strip off the end tab character.
strRow = Left(strRow, Len(strRow) - 1)
' Print the output string.
Print #1, strRow
strRow = ""
.MoveNext
Loop
End With
Close

End Sub

Create a Command Button on Your Form that Writes Records to a

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconFormatData.asp (1 of 2) [11/17/2002 11:18:51 PM]


Welcome to the MSDN Library
File
Once you've created a public method in your data-aware class, you can use it in any application that requires the same functionality. For example, by creating a public method for writing
records to a delimited text file, you can easily create a WriteToFile button on your customer address form. The command button requires a single line of code.

To create a WriteToFile button, add a command button to the form and change its Caption and Name properties to WriteToFile. Then add the following line to the command button's
WriteToFile_Click event procedure:

objDataSource.WriteToFile

The code uses the WriteToFile method you created for the CustomerDataSource class.

You may want to hide the WriteToFile button while users enter data on the form. To hide the command button during data entry, add the following code to the DataEntry_Click event
procedure:

Me.WriteToFile.Visible = False

And if you hide the WriteToFile button while users enter data, make it visible again while users view data. To do so, add the following code to the ViewData_Click event procedure:

Me.WriteToFile.Visible = True

Step by Step

This topic concludes a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. To start from the beginning, see Interacting
with Data in an ASCII Text File.

For More Information For information on data sources, see Creating Data Sources in the Component Tools Guide.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconFormatData.asp (2 of 2) [11/17/2002 11:18:51 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)

MSDN Library GO
Advanced Search Visual Basic Concepts

Converting from RDO 2.0 to ADO 2.0

See Also

Up One Level One of Microsoft's newest data access technologies is ActiveX Data Objects (ADO). ADO is a replacement for the older DAO and, in particular, RDO data access interfaces, and gives you
additional features not found in either.
ADO Compared with RDO and DAO
How to Reference ADO 2.0 in Visual Basic This chapter assumes that you're currently using RDO for data access and that you're considering migrating to ADO, and it provides you with information on how to convert your application to
The ADO 2.0 Object Model use ADO.

RDO Versus ADO in Common Data Access Scenarios


Advanced RDO/ADO Data Access Scenarios Topics

● ADO Compared with RDO and DAO

● How to Reference ADO 2.0 in Visual Basic

● The ADO 2.0 Object Model

● RDO Versus ADO in Common Data Access Scenarios

● Advanced RDO/ADO Data Access Scenarios

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconConvertingFromRDOToADO.asp [11/17/2002 11:19:17 PM]


ADO Compared with RDO and DAO

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO

Visual Basic Concepts

ADO Compared with RDO and DAO

See Also

ADO isn't automatically code-compatible with your existing data access applications. While ADO encapsulates the functionality of DAO and RDO, you must convert many of the language elements
over to ADO syntax. In some cases, this will mean only a simple conversion of some functions of your existing code. In other cases, it might be best to rewrite the application using ADO's new
features.

DAO (Data Access Objects) was the first object-oriented interface that exposed the Microsoft Jet database engine (used by Microsoft Access) and allowed Visual Basic developers to directly
connect to Access tables - as well as other databases - through ODBC. DAO is suited best for either single-system applications or for small, local deployments.

RDO (Remote Data Objects) is an object-oriented data access interface to ODBC combined with the easy-to-use style of DAO, providing an interface that exposes virtually all of ODBC’s low-level
power and flexibility. RDO is limited, though, in that it doesn't access Jet or ISAM databases very well, and that it can access relational databases only through existing ODBC drivers. However,
RDO has proven to be the interface of choice for a large number of SQL Server, Oracle, and other large relational database developers. RDO provides the objects, properties, and methods needed
to access the more complex aspects of stored procedures and complex resultsets.

ADO is the successor to DAO/RDO. Functionally ADO 2.0 is most similar to RDO, and there's generally a similar mapping between the two models. ADO "flattens" the object model used by DAO
and RDO, meaning that it contains fewer objects and more properties, methods (and arguments), and events. For example, ADO has no equivalents to the rdoEngine and rdoEnvironment objects,
which exposed the ODBC driver manager and hEnv interfaces. Nor can you currently create ODBC data sources from ADO, despite the fact that your interface might be through the ODBC OLE DB
service provider.

Much of the functionality contained in the DAO and RDO models was consolidated into single objects, making for a much simpler object model. Because of this, however, you might initially find it
difficult to find the appropriate ADO object, collection, property, method, or event. Unlike DAO and RDO, although ADO objects are hierarchical, they are also creatable outside the scope of the
hierarchy.

It should be noted, however, that ADO currently doesn't support all of DAO's functionality. ADO mostly includes RDO-style functionality to interact with OLE DB data sources, plus remoting and
DHTML technology.

In general, it's probably too early in the evolution of ADO to migrate most DAO applications (except possibly ones using ODBCDirect) to ADO right now, since ADO doesn't currently support data
definition (DDL), users, groups, and so forth. If you use DAO only for client-server applications and don't rely on the Jet database engine or use DDL, however, then you can probably migrate to
ADO now. Eventually, Microsoft will provide an ADO DDL component to aid in DAO-to-ADO migration and provide generic DDL support for OLE DB providers.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconADOComparedWithRDODAO.asp?frame=true [11/17/2002 11:19:20 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO

MSDN Library GO
Advanced Search Visual Basic Concepts

ADO Compared with RDO and DAO

See Also

Up One Level ADO isn't automatically code-compatible with your existing data access applications. While ADO encapsulates the functionality of DAO and RDO, you must convert many of the language
elements over to ADO syntax. In some cases, this will mean only a simple conversion of some functions of your existing code. In other cases, it might be best to rewrite the application using
ADO Compared with RDO and DAO ADO's new features.

How to Reference ADO 2.0 in Visual Basic


The ADO 2.0 Object Model DAO (Data Access Objects) was the first object-oriented interface that exposed the Microsoft Jet database engine (used by Microsoft Access) and allowed Visual Basic developers to directly
connect to Access tables - as well as other databases - through ODBC. DAO is suited best for either single-system applications or for small, local deployments.
RDO Versus ADO in Common Data Access Scenarios
Advanced RDO/ADO Data Access Scenarios RDO (Remote Data Objects) is an object-oriented data access interface to ODBC combined with the easy-to-use style of DAO, providing an interface that exposes virtually all of ODBC’s low-
level power and flexibility. RDO is limited, though, in that it doesn't access Jet or ISAM databases very well, and that it can access relational databases only through existing ODBC drivers.
However, RDO has proven to be the interface of choice for a large number of SQL Server, Oracle, and other large relational database developers. RDO provides the objects, properties, and
methods needed to access the more complex aspects of stored procedures and complex resultsets.

ADO is the successor to DAO/RDO. Functionally ADO 2.0 is most similar to RDO, and there's generally a similar mapping between the two models. ADO "flattens" the object model used by
DAO and RDO, meaning that it contains fewer objects and more properties, methods (and arguments), and events. For example, ADO has no equivalents to the rdoEngine and rdoEnvironment
objects, which exposed the ODBC driver manager and hEnv interfaces. Nor can you currently create ODBC data sources from ADO, despite the fact that your interface might be through the
ODBC OLE DB service provider.

Much of the functionality contained in the DAO and RDO models was consolidated into single objects, making for a much simpler object model. Because of this, however, you might initially find
it difficult to find the appropriate ADO object, collection, property, method, or event. Unlike DAO and RDO, although ADO objects are hierarchical, they are also creatable outside the scope of
the hierarchy.

It should be noted, however, that ADO currently doesn't support all of DAO's functionality. ADO mostly includes RDO-style functionality to interact with OLE DB data sources, plus remoting and
DHTML technology.

In general, it's probably too early in the evolution of ADO to migrate most DAO applications (except possibly ones using ODBCDirect) to ADO right now, since ADO doesn't currently support
data definition (DDL), users, groups, and so forth. If you use DAO only for client-server applications and don't rely on the Jet database engine or use DDL, however, then you can probably
migrate to ADO now. Eventually, Microsoft will provide an ADO DDL component to aid in DAO-to-ADO migration and provide generic DDL support for OLE DB providers.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconADOComparedWithRDODAO.asp [11/17/2002 11:19:22 PM]


How to Reference ADO in Visual Basic

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO

Visual Basic Concepts

How to Reference ADO 2.0 in Visual Basic

See Also

To gain access to the ADO 2.0 objects in Visual Basic, set a reference to the appropriate ADO type library. There are two ADO type libraries. One is called ADODB and is contained in
MSADO15.DLL. It appears in the References dialog box (available from the Project menu) as "Microsoft ActiveX Data Objects 2.0 Library". The other is called ADOR and is contained in
MSADOR15.DLL. It appears in the References dialog as "Microsoft ActiveX Data Objects Recordset 2.0 Library".

The first type library (ADODB) is the larger and more feature-rich of the two; it contains the main ADO objects and is the one you'll probably want to use in most circumstances. The second is a
"lightweight" subset of the ADODB type library that supports only recordsets. You may choose to use that library instead if you plan to manipulate only recordsets.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconHowToReferenceADOInVisualBasic.asp?frame=true [11/17/2002 11:19:28 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO

MSDN Library GO
Advanced Search Visual Basic Concepts

How to Reference ADO 2.0 in Visual Basic

See Also

Up One Level To gain access to the ADO 2.0 objects in Visual Basic, set a reference to the appropriate ADO type library. There are two ADO type libraries. One is called ADODB and is contained in
MSADO15.DLL. It appears in the References dialog box (available from the Project menu) as "Microsoft ActiveX Data Objects 2.0 Library". The other is called ADOR and is contained in
ADO Compared with RDO and DAO MSADOR15.DLL. It appears in the References dialog as "Microsoft ActiveX Data Objects Recordset 2.0 Library".

How to Reference ADO 2.0 in Visual Basic


The ADO 2.0 Object Model The first type library (ADODB) is the larger and more feature-rich of the two; it contains the main ADO objects and is the one you'll probably want to use in most circumstances. The second is
a "lightweight" subset of the ADODB type library that supports only recordsets. You may choose to use that library instead if you plan to manipulate only recordsets.
RDO Versus ADO in Common Data Access Scenarios
Advanced RDO/ADO Data Access Scenarios

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconHowToReferenceADOInVisualBasic.asp [11/17/2002 11:19:31 PM]


The ADO Object Model

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO

Visual Basic Concepts

The ADO 2.0 Object Model

See Also

The ADO 2.0 object model is composed of eight objects, most of them similar in functionality to RDO objects, only with enhanced functionality. Spend some time browsing the object model in the
Object Browser (F2) to become familiar with the location of the various properties, methods, events, collections, and so forth.

Note All objects followed by an asterisk (*) are objects that also apply to the ADO Recordset type library (ADOR).

● Command object Contains information about a command, such as a query string, parameter definition, and so forth. The Command object is similar in functionality to RDO's rdoQuery object.

● Connection object Contains information about a data provider. The Connection object is similar in functionality to RDO's rdoConnection object, and it contains the information on schema. It also contains some of the functionality of the RDOEnvironment object,
such as transaction control.

● Error object Contains extended information when an error occurs with a data provider. The Error object is similar in functionality to RDO's rdoError object. In comparison to RDO, however, the Errors collection is on the Connection object, whereas the rdoErrors
collection is on the rdoEngine object in RDO 2.0.

● Field object* Contains information about a single column of data in a recordset. The Field object is similar in functionality to RDO's rdoColumn object.

● Parameter object Contains a single parameter for a parameterized Command object. The Command object has a Parameters collection to contain all of its Parameter objects. The Parameter object is similar in functionality to RDO's rdoParameter object.

● Property object* Contains a provider-defined characteristic of an ADO object. There is no RDO equivalent to this object, but DAO has a similar object. ADO objects can have two kinds of properties:
● Built-In Properties: Properties which are "native" to ADO. That is, properties in ADO that are immediately available to any new object using the familiar MyObject.Property syntax. Built-in properties do not appear as Property objects in an object’s Properties collection, so while you can change their values, you can't modify their characteristics or delete
them.

● Dynamic properties: Properties which are not native to ADO and are defined by the underlying data provider. They appear in the Properties collection of the appropriate ADO object.

For example, a property specific to the data provider may indicate if a Recordset object supports transactions or updating. These additional properties appear as Property objects in the Recordset’s Properties collection. Dynamic properties can be referred to only through the collection using the MyObject.Properties(0) or MyObject.Properties("Name")
syntax. Different data providers may implement one or more special properties to deal with special provider-specific operations.

● Recordset object* The Recordset object contains records returned from a query as well as a cursor into those records. The Recordset object is similar in functionality to RDO's rdoResultset object. You can open a Recordset (for example, perform a query)
without explicitly opening a Connection object. If, however, you choose to create a Connection object, you can open multiple Recordset objects on the same connection.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconTheADOObjectModel.asp?frame=true [11/17/2002 11:19:35 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO

MSDN Library GO
Advanced Search Visual Basic Concepts

The ADO 2.0 Object Model

See Also

Up One Level The ADO 2.0 object model is composed of eight objects, most of them similar in functionality to RDO objects, only with enhanced functionality. Spend some time browsing the object model in
the Object Browser (F2) to become familiar with the location of the various properties, methods, events, collections, and so forth.
ADO Compared with RDO and DAO
How to Reference ADO 2.0 in Visual Basic Note All objects followed by an asterisk (*) are objects that also apply to the ADO Recordset type library (ADOR).
The ADO 2.0 Object Model
RDO Versus ADO in Common Data Access Scenarios ● Command object Contains information about a command, such as a query string, parameter definition, and so forth. The Command object is similar in functionality to RDO's rdoQuery object.

Advanced RDO/ADO Data Access Scenarios ● Connection object Contains information about a data provider. The Connection object is similar in functionality to RDO's rdoConnection object, and it contains the information on schema. It also contains some of the functionality of the RDOEnvironment
object, such as transaction control.

● Error object Contains extended information when an error occurs with a data provider. The Error object is similar in functionality to RDO's rdoError object. In comparison to RDO, however, the Errors collection is on the Connection object, whereas the
rdoErrors collection is on the rdoEngine object in RDO 2.0.

● Field object* Contains information about a single column of data in a recordset. The Field object is similar in functionality to RDO's rdoColumn object.

● Parameter object Contains a single parameter for a parameterized Command object. The Command object has a Parameters collection to contain all of its Parameter objects. The Parameter object is similar in functionality to RDO's rdoParameter object.

● Property object* Contains a provider-defined characteristic of an ADO object. There is no RDO equivalent to this object, but DAO has a similar object. ADO objects can have two kinds of properties:
● Built-In Properties: Properties which are "native" to ADO. That is, properties in ADO that are immediately available to any new object using the familiar MyObject.Property syntax. Built-in properties do not appear as Property objects in an object’s Properties collection, so while you can change their values, you can't modify their characteristics or
delete them.

● Dynamic properties: Properties which are not native to ADO and are defined by the underlying data provider. They appear in the Properties collection of the appropriate ADO object.

For example, a property specific to the data provider may indicate if a Recordset object supports transactions or updating. These additional properties appear as Property objects in the Recordset’s Properties collection. Dynamic properties can be referred to only through the collection using the MyObject.Properties(0) or
MyObject.Properties("Name") syntax. Different data providers may implement one or more special properties to deal with special provider-specific operations.

● Recordset object* The Recordset object contains records returned from a query as well as a cursor into those records. The Recordset object is similar in functionality to RDO's rdoResultset object. You can open a Recordset (for example, perform a query)
without explicitly opening a Connection object. If, however, you choose to create a Connection object, you can open multiple Recordset objects on the same connection.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconTheADOObjectModel.asp [11/17/2002 11:19:38 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO

MSDN Library GO
Advanced Search Visual Basic Concepts

RDO Versus ADO in Common Data Access Scenarios

See Also

Up One Level Three basic data access scenarios are listed below, and each one is discussed in a succeeding topic. In each scenario, an RDO approach to the problem is shown, followed by an ADO approach.

Establishing a Connection to a Database


Running a Basic Query ●


Establishing a Connection to a Database

Running a Basic Query

Displaying a Resultset in an MSHFlexGrid Control ● Displaying a Resultset in an MSHFlexGrid control

Note Some of these examples refer to additional controls on a form, such as an MSHFlexGrid control or a TextBox control. Add these controls to your project to make the projects work
correctly.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRDOVersusADOInCommonDataAccessScenarios.asp [11/17/2002 11:19:44 PM]


Establishing a Connection to a Database

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > RDO Versus ADO in Common Data Access Scenarios

Visual Basic Concepts

Establishing a Connection to a Database

See Also

RDO

To open a connection, you must supply a connection string with parameters. Note that a connection is not required by RDO to create an rdoQuery object, but is required to initially create an
rdoResultset object:

Dim cn As New rdoConnection


Dim cnB As New rdoConnection
Const ConnectString = "uid=myname;pwd=mypw;driver={SQLServer};" & _
"server=myserver;database=pubs;dsn=''"

This connect string accesses a specific SQL Server and permits ODBC to open a connection without a DSN. This is a typical ODBC connect string with all of the standard arguments.

The next section, in the form's Load event, establishes the type of cursor driver and the login timeout. By default, RDO uses the rdUseIfNeeded cursor type, which invokes server-side cursors on
SQL Server. This default is overridden in the example below by specifying rdUseNone. The rdDriverNoPrompt flag means that the application generates an error if the user ID and password do not
match.

Private Sub Form_Load()


With cn
cn.Connect = ConnectString
cn.LoginTimeout = 10
cn.CursorDriver = rdUseNone
cn.EstablishConnection rdDriverNoPrompt
End With

This second connection performs any client-batch updates:

With cnB
cnB.Connect = ConnectString
cnB.CursorDriver = rdUseClientBatch
cnB.EstablishConnection
End With
End Sub

The last event occurs when the connection operation completes and it handles any errors that occur when the connection is opened. With it, you can test to see if the connection worked, and if so,
enable any buttons that rely on an open connection.

Private Sub cn_Connect(ByVal ErrorOccurred As Boolean)


If ErrorOccurred Then
MsgBox "Could not open connection", vbCritical
Else
RunOKFrame.Enabled = True
End If
End Sub

ADO

To establish a database connection in ADO, first create a set of ADO objects referenced from the ADODB object. These are used later to set specific properties that open connections and generate
resultsets:

Dim cn As New ADODB.Connection


Dim rs As New ADODB.Recordset
Dim cnB As New ADODB.Connection
Dim Qy As New ADODB.Command

The next line creates a connect string, just like the one you created in the previous RDO example. In both cases, you are using ODBC’s "non-DSN" connection strategy to save time and increase
performance:

Const ConnectString = "uid=myname;pwd=mypw;driver={SQL Server};" & _


"server=myserver;database=pubs;dsn=''"

The following declarations initialize the variables used in this example. (Note the creation of a variant array to hold the resultset):

Dim sql As String


Dim rc As Integer

http://msdn.microsoft.com/library/en-us/vbcon98/...nEstablishingConnectionToDatabase.asp?frame=true (1 of 2) [11/17/2002 11:19:47 PM]


Establishing a Connection to a Database

Dim i As Integer
Dim Changes As Integer
Dim bms() As Variant

Next, open an ADO connection to a database in the Form_Load event. Note that this code is very similar to the RDO code except that the constants are prefaced with "ad" rather than "rd". To see
all available constants, look at the ADODB type library.

Note There's no need to specify the prompting behavior since ADO defaults to "no prompt". If you elect to change this, however, use the ADO Properties collection to deal with the desired
prompt behavior. In RDO, you can set the behavior using the OpenConnection argument. In ADO, you must set the Properties ("Prompt") property.

Also, there's no need to specify a cursor driver if you don't want to use one (such as the RDO CursorDriver = rdUseNone), since ADO defaults to no cursor driver by default.

Private Sub Form_Load()


With cn
' Establish DSN-less connection
.ConnectString = ConnectString
.ConnectionTimeout = 10
'.Properties("Prompt") = adPromptNever
' This is the default prompting mode in ADO.
.Open
End With
With cnB
.ConnectString = ConnectString
.CursorLocation = adUseClient
.Open
End With
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/...nEstablishingConnectionToDatabase.asp?frame=true (2 of 2) [11/17/2002 11:19:47 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > RDO Versus ADO in Common Data Access Scenarios

MSDN Library GO
Advanced Search Visual Basic Concepts

Establishing a Connection to a Database

See Also

Up One Level RDO

Establishing a Connection to a Database


To open a connection, you must supply a connection string with parameters. Note that a connection is not required by RDO to create an rdoQuery object, but is required to initially create an
Running a Basic Query rdoResultset object:

Displaying a Resultset in an MSHFlexGrid Control


Dim cn As New rdoConnection
Dim cnB As New rdoConnection
Const ConnectString = "uid=myname;pwd=mypw;driver={SQLServer};" & _
"server=myserver;database=pubs;dsn=''"

This connect string accesses a specific SQL Server and permits ODBC to open a connection without a DSN. This is a typical ODBC connect string with all of the standard arguments.

The next section, in the form's Load event, establishes the type of cursor driver and the login timeout. By default, RDO uses the rdUseIfNeeded cursor type, which invokes server-side cursors
on SQL Server. This default is overridden in the example below by specifying rdUseNone. The rdDriverNoPrompt flag means that the application generates an error if the user ID and password
do not match.

Private Sub Form_Load()


With cn
cn.Connect = ConnectString
cn.LoginTimeout = 10
cn.CursorDriver = rdUseNone
cn.EstablishConnection rdDriverNoPrompt
End With

This second connection performs any client-batch updates:

With cnB
cnB.Connect = ConnectString
cnB.CursorDriver = rdUseClientBatch
cnB.EstablishConnection
End With
End Sub

The last event occurs when the connection operation completes and it handles any errors that occur when the connection is opened. With it, you can test to see if the connection worked, and if
so, enable any buttons that rely on an open connection.

Private Sub cn_Connect(ByVal ErrorOccurred As Boolean)


If ErrorOccurred Then
MsgBox "Could not open connection", vbCritical
Else
RunOKFrame.Enabled = True
End If
End Sub

ADO

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconEstablishingConnectionToDatabase.asp (1 of 2) [11/17/2002 11:19:49 PM]


Welcome to the MSDN Library
To establish a database connection in ADO, first create a set of ADO objects referenced from the ADODB object. These are used later to set specific properties that open connections and
generate resultsets:

Dim cn As New ADODB.Connection


Dim rs As New ADODB.Recordset
Dim cnB As New ADODB.Connection
Dim Qy As New ADODB.Command

The next line creates a connect string, just like the one you created in the previous RDO example. In both cases, you are using ODBC’s "non-DSN" connection strategy to save time and
increase performance:

Const ConnectString = "uid=myname;pwd=mypw;driver={SQL Server};" & _


"server=myserver;database=pubs;dsn=''"

The following declarations initialize the variables used in this example. (Note the creation of a variant array to hold the resultset):

Dim sql As String


Dim rc As Integer
Dim i As Integer
Dim Changes As Integer
Dim bms() As Variant

Next, open an ADO connection to a database in the Form_Load event. Note that this code is very similar to the RDO code except that the constants are prefaced with "ad" rather than "rd". To
see all available constants, look at the ADODB type library.

Note There's no need to specify the prompting behavior since ADO defaults to "no prompt". If you elect to change this, however, use the ADO Properties collection to deal with the desired
prompt behavior. In RDO, you can set the behavior using the OpenConnection argument. In ADO, you must set the Properties ("Prompt") property.

Also, there's no need to specify a cursor driver if you don't want to use one (such as the RDO CursorDriver = rdUseNone), since ADO defaults to no cursor driver by default.

Private Sub Form_Load()


With cn
' Establish DSN-less connection
.ConnectString = ConnectString
.ConnectionTimeout = 10
'.Properties("Prompt") = adPromptNever
' This is the default prompting mode in ADO.
.Open
End With
With cnB
.ConnectString = ConnectString
.CursorLocation = adUseClient
.Open
End With
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconEstablishingConnectionToDatabase.asp (2 of 2) [11/17/2002 11:19:49 PM]


Running a Basic Query

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > RDO Versus ADO in Common Data Access Scenarios

Visual Basic Concepts

Running a Basic Query

See Also

RDO

This event procedure returns a resultset based on an SQL statement. It performs a restricted query and passes the resultset to a control that inserts the resultant data into an MSHFlexGrid control.
Note that building a resultset requires an open connection.

Private Sub RunButton_Click()


Dim rs As rdoResultset
Set rs = cn.OpenResultset("select * from titles where title _
like '%h'")
rdoGrid1.ShowData rs
rs.Close
End Sub

ADO

Once the database connection is open, you can run a query against it. The following event procedure is very similar to the previous RDO code. In this case, however, you use the new ADO Open
method that takes the SQL query and the ADO Connection object as arguments, rather than using the rdoConnection object's OpenResultset method. You can also opt to use the ADO Connection
object’s Execute method, just as you could in RDO (as long as it didn’t return a rowset).

A primary difference of ADO2 compared with RDO2 is that ADO2 allows you to create a recordset and set its properties before you open the recordset.

Private Sub RunButton_Click()


Dim rs As New ADODB.Recordset
rs.Open "select * from titles where title like '%h'", cn
ADOGrid1.ShowData rs
rs.Close
End Sub

You can run this query and process its resultset asynchronously in ADO. That is, when you specify the adFetchAsynch option on rs.Open, ADO causes the cursor provider to automatically populate
the resultset in the background.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconRunningBasicQuery.asp?frame=true [11/17/2002 11:19:54 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > RDO Versus ADO in Common Data Access Scenarios

MSDN Library GO
Advanced Search Visual Basic Concepts

Running a Basic Query

See Also

Up One Level RDO

Establishing a Connection to a Database


This event procedure returns a resultset based on an SQL statement. It performs a restricted query and passes the resultset to a control that inserts the resultant data into an MSHFlexGrid
Running a Basic Query control. Note that building a resultset requires an open connection.

Displaying a Resultset in an MSHFlexGrid Control


Private Sub RunButton_Click()
Dim rs As rdoResultset
Set rs = cn.OpenResultset("select * from titles where title _
like '%h'")
rdoGrid1.ShowData rs
rs.Close
End Sub

ADO

Once the database connection is open, you can run a query against it. The following event procedure is very similar to the previous RDO code. In this case, however, you use the new ADO
Open method that takes the SQL query and the ADO Connection object as arguments, rather than using the rdoConnection object's OpenResultset method. You can also opt to use the ADO
Connection object’s Execute method, just as you could in RDO (as long as it didn’t return a rowset).

A primary difference of ADO2 compared with RDO2 is that ADO2 allows you to create a recordset and set its properties before you open the recordset.

Private Sub RunButton_Click()


Dim rs As New ADODB.Recordset
rs.Open "select * from titles where title like '%h'", cn
ADOGrid1.ShowData rs
rs.Close
End Sub

You can run this query and process its resultset asynchronously in ADO. That is, when you specify the adFetchAsynch option on rs.Open, ADO causes the cursor provider to automatically
populate the resultset in the background.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRunningBasicQuery.asp [11/17/2002 11:19:56 PM]


Displaying a Resultset in an MSHFlexGrid Control

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > RDO Versus ADO in Common Data Access Scenarios

Visual Basic Concepts

Displaying a Resultset in an MSHFlexGrid Control

See Also

RDO

The following code uses the ShowData method of a custom ActiveX control to display data from a resultset in an MSHFlexGrid control. The code sets up the grid based on the names in the
rdoColumns property and initializes the grid, preparing it for the data. Note the use of the OrdinalPosition property to index the resultset's rdoColumns property.

There are two sets of code to extract data from the rdoResultset, one that uses GetClipString, and another that uses the GetRows method. This helps you compare different approaches to the
situation.

Public Function ShowData(Resultset As rdoResultset) As Variant


Dim cl As rdoColumn
Static GridSetup As Boolean
Dim MaxL As Integer
Dim rsl As rdoResultset
Dim Rows As Variant
On Error GoTo ShowDataEH
Set rsl = Resultset
If GridSetup = False Then
FGrid1.Rows = 51
FGrid1.Cols = rsl.rdoColumns.Count
FGrid1.Row = 0
For Each cl In rsl.rdoColumns
FGrid1.Col = cl.OrdinalPosition - 1
FGrid1 = cl.Name
If rsl.rdoColumns(cl.OrdinalPosition - 1).ChunkRequired Then
MaxL = 1
Else
MaxL = rsl.rdoColumns(cl.OrdinalPosition - 1).Size + 4
End If
If MaxL > 20 Then MaxL = 20
FGrid1.ColWidth(FGrid1.Col) = TextWidth(String(MaxL, "n"))
Next cl
GridSetup = True
End If
FGrid1.Rows = 1 'Clear Grid of data (except titles)
FGrid1.Rows = 51
FGrid1.Row = 1
FGrid1.Col = 0
FGrid1.RowSel = FGrid1.Rows - 1
FGrid1.ColSel = FGrid1.Cols - 1
FGrid1.Clip = rsl.GetClipString(50, , , "-")

ExitShowData:
FGrid1.RowSel = 1
FGrid1.ColSel = 0
Exit Function

ShowDataEH:
Select Case Err
Case 40022:
FGrid1.Clear
Resume ExitShowData
Case 13
FGrid1.Text = "< >"
Resume Next
Case Else
MsgBox "Could not display data: " & Err & vbCrLf & Error$
Resume ' ExitShowData
End Select
End Function

ADO

The following code implements the ShowData method of a custom ActiveX control adapted from an RDO control. Note that the RDO GetClipString method is superseded in ADO by the GetString
method. Since you then have to parse the resulting Variant array, the routine is noticeably slower. If you have problems getting the GetRows function to work, you should convert to a more
conservative (and slower) approach that loops through the rows. However, you should avoid using this technique if possible because it is far less efficient than using GetRows or binding directly to
a control.

Note how the OrdinalPosition property can no longer be used as an index on the Fields collection to pull out the column titles as you could in RDO. To handle this, substitute a new integer counter
to address the column being manipulated. Use the DefinedSize and ActualSize properties to find the TEXT and IMAGE datatype fields that would not fit in a column. These new properties make it
easier to determine the details of specific field values. Also added is code to deal with BLOB types if they're encountered while working through the data columns.

Public Function ShowData(Resultset As Recordset) As Variant


Dim cl As Field
Static GridSetup As Boolean
Dim MaxL As Integer
Dim Op As Integer
Dim rsl As Recordset
Dim rows As Variant

http://msdn.microsoft.com/library/en-us/vbcon98/ht...playingResultsetInMSFlexGridControl.asp?frame=true (1 of 2) [11/17/2002 11:20:01 PM]


Displaying a Resultset in an MSHFlexGrid Control
On Error GoTo ShowDataEH
Set rsl = Resultset

If GridSetup = False Then


FGrid1.rows = 51
FGrid1.Cols = rsl.Fields.Count
FGrid1.Row = 0
Op = 0
For Each cl In rsl.Fields
FGrid1.Col = Op
FGrid1 = cl.Name
If rsl.Fields(Op).DefinedSize > 255 Then
MaxL = 1
Else
MaxL = rsl.Fields(Op).ActualSize + 4
End If
If MaxL > 20 Then MaxL = 20
FGrid1.ColWidth(FGrid1.Col) = TextWidth(String(MaxL, "n"))
Op = Op + 1
Next cl
GridSetup = True
End If
FGrid1.rows = 1
FGrid1.rows = 51
FGrid1.Row = 1
FGrid1.Col = 0
FGrid1.RowSel = FGrid1.rows - 1
FGrid1.ColSel = FGrid1.Cols - 1
With FGrid1
' You can also use the ADO2 GetString method here in lieu of the
' following.
FGrid1.Clip = rsl.GetString(adClipString, 50, , , "-")
End With

ExitShowData:
FGrid1.RowSel = 1
FGrid1.ColSel = 0
Exit Function

ShowDataEH:
Select Case Err
Case 3021:
FGrid1.Clear
Resume ExitShowData
Case 13, Is < 0
rows(j, i) = "< >"
Resume 'Next
Case Else
MsgBox "Could not display data: " & Err & vbCrLf & Error$
Resume ' ExitShowData
End Select
End Function

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/ht...playingResultsetInMSFlexGridControl.asp?frame=true (2 of 2) [11/17/2002 11:20:01 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > RDO Versus ADO in Common Data Access Scenarios

MSDN Library GO
Advanced Search Visual Basic Concepts

Displaying a Resultset in an MSHFlexGrid Control

See Also

Up One Level RDO

Establishing a Connection to a Database


The following code uses the ShowData method of a custom ActiveX control to display data from a resultset in an MSHFlexGrid control. The code sets up the grid based on the names in the
Running a Basic Query rdoColumns property and initializes the grid, preparing it for the data. Note the use of the OrdinalPosition property to index the resultset's rdoColumns property.

Displaying a Resultset in an MSHFlexGrid Control


There are two sets of code to extract data from the rdoResultset, one that uses GetClipString, and another that uses the GetRows method. This helps you compare different approaches to the
situation.

Public Function ShowData(Resultset As rdoResultset) As Variant


Dim cl As rdoColumn
Static GridSetup As Boolean
Dim MaxL As Integer
Dim rsl As rdoResultset
Dim Rows As Variant
On Error GoTo ShowDataEH
Set rsl = Resultset
If GridSetup = False Then
FGrid1.Rows = 51
FGrid1.Cols = rsl.rdoColumns.Count
FGrid1.Row = 0
For Each cl In rsl.rdoColumns
FGrid1.Col = cl.OrdinalPosition - 1
FGrid1 = cl.Name
If rsl.rdoColumns(cl.OrdinalPosition - 1).ChunkRequired Then
MaxL = 1
Else
MaxL = rsl.rdoColumns(cl.OrdinalPosition - 1).Size + 4
End If
If MaxL > 20 Then MaxL = 20
FGrid1.ColWidth(FGrid1.Col) = TextWidth(String(MaxL, "n"))
Next cl
GridSetup = True
End If
FGrid1.Rows = 1 'Clear Grid of data (except titles)
FGrid1.Rows = 51
FGrid1.Row = 1
FGrid1.Col = 0
FGrid1.RowSel = FGrid1.Rows - 1
FGrid1.ColSel = FGrid1.Cols - 1
FGrid1.Clip = rsl.GetClipString(50, , , "-")

ExitShowData:
FGrid1.RowSel = 1
FGrid1.ColSel = 0
Exit Function

ShowDataEH:
Select Case Err
Case 40022:
FGrid1.Clear
Resume ExitShowData
Case 13
FGrid1.Text = "< >"
Resume Next
Case Else
MsgBox "Could not display data: " & Err & vbCrLf & Error$
Resume ' ExitShowData

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDisplayingResultsetInMSFlexGridControl.asp (1 of 2) [11/17/2002 11:20:04 PM]


Welcome to the MSDN Library
End Select
End Function

ADO

The following code implements the ShowData method of a custom ActiveX control adapted from an RDO control. Note that the RDO GetClipString method is superseded in ADO by the
GetString method. Since you then have to parse the resulting Variant array, the routine is noticeably slower. If you have problems getting the GetRows function to work, you should convert to
a more conservative (and slower) approach that loops through the rows. However, you should avoid using this technique if possible because it is far less efficient than using GetRows or binding
directly to a control.

Note how the OrdinalPosition property can no longer be used as an index on the Fields collection to pull out the column titles as you could in RDO. To handle this, substitute a new integer
counter to address the column being manipulated. Use the DefinedSize and ActualSize properties to find the TEXT and IMAGE datatype fields that would not fit in a column. These new
properties make it easier to determine the details of specific field values. Also added is code to deal with BLOB types if they're encountered while working through the data columns.

Public Function ShowData(Resultset As Recordset) As Variant


Dim cl As Field
Static GridSetup As Boolean
Dim MaxL As Integer
Dim Op As Integer
Dim rsl As Recordset
Dim rows As Variant
On Error GoTo ShowDataEH
Set rsl = Resultset

If GridSetup = False Then


FGrid1.rows = 51
FGrid1.Cols = rsl.Fields.Count
FGrid1.Row = 0
Op = 0
For Each cl In rsl.Fields
FGrid1.Col = Op
FGrid1 = cl.Name
If rsl.Fields(Op).DefinedSize > 255 Then
MaxL = 1
Else
MaxL = rsl.Fields(Op).ActualSize + 4
End If
If MaxL > 20 Then MaxL = 20
FGrid1.ColWidth(FGrid1.Col) = TextWidth(String(MaxL, "n"))
Op = Op + 1
Next cl
GridSetup = True
End If
FGrid1.rows = 1
FGrid1.rows = 51
FGrid1.Row = 1
FGrid1.Col = 0
FGrid1.RowSel = FGrid1.rows - 1
FGrid1.ColSel = FGrid1.Cols - 1
With FGrid1
' You can also use the ADO2 GetString method here in lieu of the
' following.
FGrid1.Clip = rsl.GetString(adClipString, 50, , , "-")
End With

ExitShowData:
FGrid1.RowSel = 1
FGrid1.ColSel = 0
Exit Function

ShowDataEH:
Select Case Err
Case 3021:
FGrid1.Clear
Resume ExitShowData
Case 13, Is < 0
rows(j, i) = "< >"
Resume 'Next
Case Else
MsgBox "Could not display data: " & Err & vbCrLf & Error$
Resume ' ExitShowData
End Select
End Function

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDisplayingResultsetInMSFlexGridControl.asp (2 of 2) [11/17/2002 11:20:04 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO

MSDN Library GO
Advanced Search Visual Basic Concepts

Advanced RDO/ADO Data Access Scenarios

See Also

Up One Level Following are five data access scenarios that are more complex than simple Select queries. Each one is discussed in a succeeding topic. First, an RDO approach to the problem is shown,
followed by the ADO solution so that you can compare how each is accomplished.
Executing a Parameter Query
Performing a Parameter-Driven Stored Procedure ● Executing a Parameter Query

Running a Stored Procedure That Returns Multiple Resultsets ● Performing a Parameter-Driven Stored Procedure

Running a Stored Procedure That Returns Multiple Resultsets


Performing an Action Query

● Performing an Action Query

Running an Optimistic Batch Query ● Running an Optimistic Batch Query

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconMoreAdvancedRDOADODataAccessScenarios.asp [11/17/2002 11:20:13 PM]


Performing a Parameter Query

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > Advanced RDO/ADO Data Access Scenarios

Visual Basic Concepts

Executing a Parameter Query

See Also

RDO

The procedure below illustrates a method for performing a parameterized Select query: that is, a SELECT statement that requires one or more parameters. This process is done in two steps:

1. Build a query that expects a parameter, pass in the first parameter, then perform the query.

2. Perform the query again with new parameters.

The first time the query is called, RDO attempts to create a new RDO query object. Since the object is appended to the rdoConnection object’s rdoQueries collection, you can reference it each time
the procedure is called. Each subsequent time the procedure is called, the Refresh method re-executes the query. This technique builds a temporary stored procedure (SP) behind the scenes that
is referenced by the Requery method. The temporary SP is dropped when the connection is closed.

Private Sub ParmQueryButton_Click()


Dim Qy As New rdoQuery
Dim rs As rdoResultset
Static FirstTime As Boolean
If cn.rdoQueries.Count = 0 Then
FirstTime = True
sql = "select * from authors where year_born = ?"
Set Qy = cn.CreateQuery("Pq", sql)
End If
Qy(0) = QueryParam.Text
If FirstTime Then
Set rs = Qy.OpenResultset()
FirstTime = False
Else
rs.Requery
End If
rdoGrid1.ShowData rs
rs.Close
End Sub

ADO

This procedure is designed to perform a table-access query that accepts a parameter. You use the "?" character (as in the previous RDO example) to indicate where the parameter is to be placed.
In this case, though, you don't create an rdoQuery object that is kept in a collection off the rdoConnection object; you instead use a stand-alone ADO Command object created (and scoped)
earlier. The first time through, you set up the Command properties, and each time thereafter, you simply execute the command after having changed the parameter.

ADO gives you a lot of flexibility here—more, in some cases than RDO. If you tell ADO everything it needs to know about a query, it won't have to perform informational queries against the
database to get missing information, so queries run faster.

Note You don’t have to build the ADO Parameters collection in code, since it's automatically created for you just like when you use RDO. However, it is possible to do so, and doing so can
improve performance, at the cost of a little code complexity. If you elect to do it, make sure that the Command is associated with an open connection so ADO can query the service provider (and
the server) for the parameter's description.

To run the query and create the resultset, use the Execute method on the Command object.

Private Sub ParmQueryButton_Click()


If Cmd.CommandText = "" Then
Cmd.ActiveConnection = cn
With Cmd
.CommandText = "select * from authors where year_born = ?"
.CommandType = adCmdText
.CommandTimeout = 15
End With
'
' The following section of code is not required,
' but can make execution faster. It eliminates the need
' for ADO to fetch the parameter metrics from the server.
'
With Parm
.Type = adInteger
.Size = 4
.Direction = adParamInput
.Value = QueryParam.Text
Cmd.Parameters.Append Parm
End With
End If

Cmd.Parameters(0).Value = QueryParam.Text
Set rs = Cmd.Execute()
ADOGrid1.ShowData rs
rs.Close
End Sub

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconPerformingParameterQuery.asp?frame=true (1 of 2) [11/17/2002 11:20:16 PM]


Performing a Parameter Query

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconPerformingParameterQuery.asp?frame=true (2 of 2) [11/17/2002 11:20:16 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > Advanced RDO/ADO Data Access Scenarios

MSDN Library GO
Advanced Search Visual Basic Concepts

Executing a Parameter Query

See Also

Up One Level RDO

Executing a Parameter Query


The procedure below illustrates a method for performing a parameterized Select query: that is, a SELECT statement that requires one or more parameters. This process is done in two steps:
Performing a Parameter-Driven Stored Procedure
Running a Stored Procedure That Returns Multiple Resultsets
1. Build a query that expects a parameter, pass in the first parameter, then perform the query.

Performing an Action Query 2. Perform the query again with new parameters.

Running an Optimistic Batch Query


The first time the query is called, RDO attempts to create a new RDO query object. Since the object is appended to the rdoConnection object’s rdoQueries collection, you can reference it each
time the procedure is called. Each subsequent time the procedure is called, the Refresh method re-executes the query. This technique builds a temporary stored procedure (SP) behind the
scenes that is referenced by the Requery method. The temporary SP is dropped when the connection is closed.

Private Sub ParmQueryButton_Click()


Dim Qy As New rdoQuery
Dim rs As rdoResultset
Static FirstTime As Boolean
If cn.rdoQueries.Count = 0 Then
FirstTime = True
sql = "select * from authors where year_born = ?"
Set Qy = cn.CreateQuery("Pq", sql)
End If
Qy(0) = QueryParam.Text
If FirstTime Then
Set rs = Qy.OpenResultset()
FirstTime = False
Else
rs.Requery
End If
rdoGrid1.ShowData rs
rs.Close
End Sub

ADO

This procedure is designed to perform a table-access query that accepts a parameter. You use the "?" character (as in the previous RDO example) to indicate where the parameter is to be
placed. In this case, though, you don't create an rdoQuery object that is kept in a collection off the rdoConnection object; you instead use a stand-alone ADO Command object created (and
scoped) earlier. The first time through, you set up the Command properties, and each time thereafter, you simply execute the command after having changed the parameter.

ADO gives you a lot of flexibility here—more, in some cases than RDO. If you tell ADO everything it needs to know about a query, it won't have to perform informational queries against the
database to get missing information, so queries run faster.

Note You don’t have to build the ADO Parameters collection in code, since it's automatically created for you just like when you use RDO. However, it is possible to do so, and doing so can
improve performance, at the cost of a little code complexity. If you elect to do it, make sure that the Command is associated with an open connection so ADO can query the service provider
(and the server) for the parameter's description.

To run the query and create the resultset, use the Execute method on the Command object.

Private Sub ParmQueryButton_Click()


If Cmd.CommandText = "" Then
Cmd.ActiveConnection = cn
With Cmd
.CommandText = "select * from authors where year_born = ?"
.CommandType = adCmdText

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconPerformingParameterQuery.asp (1 of 2) [11/17/2002 11:20:18 PM]


Welcome to the MSDN Library
.CommandTimeout = 15
End With
'
' The following section of code is not required,
' but can make execution faster. It eliminates the need
' for ADO to fetch the parameter metrics from the server.
'
With Parm
.Type = adInteger
.Size = 4
.Direction = adParamInput
.Value = QueryParam.Text
Cmd.Parameters.Append Parm
End With
End If

Cmd.Parameters(0).Value = QueryParam.Text
Set rs = Cmd.Execute()
ADOGrid1.ShowData rs
rs.Close
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconPerformingParameterQuery.asp (2 of 2) [11/17/2002 11:20:18 PM]


Performing a Parameter-Driven Stored Procedure

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > Advanced RDO/ADO Data Access Scenarios

Visual Basic Concepts

Performing a Parameter-Driven Stored Procedure

See Also

RDO

Since many client/server applications depend heavily on stored procedures (SP), a data access interface should be able to perform them quickly and efficiently. Stored procedures, however, can be
tricky to handle. In some cases, stored procedures require management of OUTPUT and return status values and other, more conventional arguments. In addition, an SP can return several
complex resultsets, including PRINT or RAISERROR statement return values. In some cases, it's better to create complex SPs, while in others it’s better and easier to keep SPs simpler and more
modular and use Visual Basic to tie them together.

The code below shows the RDO approach to these problems. First, it performs a simple parameter-based SP and shows the results in the grid. Some accommodations are made to the subsequent
ADO design, and these are noted. It uses the same connections established in the earlier examples.

Note that the code requires us to include a correct ODBC "Call" statement. Again, this is not necessary in the UserConnection designer, but it’s essential in the RDO code-based approach. Here,
you use the stand-alone rdoQuery object and assign the already open Connection to it. The rdoQuery object can then be used in subsequent calls to handle a parameter query.

Note also that the code does not attempt to refer to the return status argument. This value is not available until the resultset is fully populated; only then does SQL Server return this value.

Private Sub RunSPButton_Click()


Dim Qy As New rdoQuery
Dim rs As rdoResultset
sql = "{? = Call AuthorByYearBorn (?,?)}"
Set Qy.ActiveConnection = cn
Qy.sql = sql
Qy.rdoParameters(0).Direction = rdParamReturnValue
Qy(1) = "1947"
Qy(2) = "1948"
Set rs = Qy.OpenResultset()
rdoGrid1.ShowData rs
ShowRows = rs.RowCount
rs.Close
End Sub

ADO

ADO has a lot of flexibility when it comes to performing stored procedures. But this flexibility comes at the cost of more code. As with the previous example ("Performing a Parameter Query"), it's
possible to build your own ADODB Parameters collection. In this case, you’re performing a simple two-argument SP, "AuthorByYearBorn", that returns a small resultset. Note that although ADO
allows you to create your own parameters, it's not necessary to do so.

Note ADO collections are 0-based to match DAO. RDO collections are 1-based.

Private Sub RunSPButton_Click()


Dim Qy As New ADODB.Command
Dim Parm As New ADODB.Parameter
Dim Parm2 As New ADODB.Parameter

Set Qy.ActiveConnection = cn
Qy(0)="1947"
Qy(1)="1948"
Qy.CommandType = adCmdStoredProc
Qy.CommandText = "AuthorByYearBorn"

Set rs = Qy.Execute(ShowRows)
ADOGrid1.ShowData rs
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/...rformingParameterDrivenStoredProcedure.asp?frame=true [11/17/2002 11:20:22 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > Advanced RDO/ADO Data Access Scenarios

MSDN Library GO
Advanced Search Visual Basic Concepts

Performing a Parameter-Driven Stored Procedure

See Also

Up One Level RDO

Executing a Parameter Query


Since many client/server applications depend heavily on stored procedures (SP), a data access interface should be able to perform them quickly and efficiently. Stored procedures, however,
Performing a Parameter-Driven Stored Procedure can be tricky to handle. In some cases, stored procedures require management of OUTPUT and return status values and other, more conventional arguments. In addition, an SP can return
several complex resultsets, including PRINT or RAISERROR statement return values. In some cases, it's better to create complex SPs, while in others it’s better and easier to keep SPs simpler
Running a Stored Procedure That Returns Multiple Resultsets and more modular and use Visual Basic to tie them together.

Performing an Action Query


Running an Optimistic Batch Query The code below shows the RDO approach to these problems. First, it performs a simple parameter-based SP and shows the results in the grid. Some accommodations are made to the
subsequent ADO design, and these are noted. It uses the same connections established in the earlier examples.

Note that the code requires us to include a correct ODBC "Call" statement. Again, this is not necessary in the UserConnection designer, but it’s essential in the RDO code-based approach.
Here, you use the stand-alone rdoQuery object and assign the already open Connection to it. The rdoQuery object can then be used in subsequent calls to handle a parameter query.

Note also that the code does not attempt to refer to the return status argument. This value is not available until the resultset is fully populated; only then does SQL Server return this value.

Private Sub RunSPButton_Click()


Dim Qy As New rdoQuery
Dim rs As rdoResultset
sql = "{? = Call AuthorByYearBorn (?,?)}"
Set Qy.ActiveConnection = cn
Qy.sql = sql
Qy.rdoParameters(0).Direction = rdParamReturnValue
Qy(1) = "1947"
Qy(2) = "1948"
Set rs = Qy.OpenResultset()
rdoGrid1.ShowData rs
ShowRows = rs.RowCount
rs.Close
End Sub

ADO

ADO has a lot of flexibility when it comes to performing stored procedures. But this flexibility comes at the cost of more code. As with the previous example ("Performing a Parameter Query"),
it's possible to build your own ADODB Parameters collection. In this case, you’re performing a simple two-argument SP, "AuthorByYearBorn", that returns a small resultset. Note that although
ADO allows you to create your own parameters, it's not necessary to do so.

Note ADO collections are 0-based to match DAO. RDO collections are 1-based.

Private Sub RunSPButton_Click()


Dim Qy As New ADODB.Command
Dim Parm As New ADODB.Parameter
Dim Parm2 As New ADODB.Parameter

Set Qy.ActiveConnection = cn
Qy(0)="1947"
Qy(1)="1948"
Qy.CommandType = adCmdStoredProc
Qy.CommandText = "AuthorByYearBorn"

Set rs = Qy.Execute(ShowRows)
ADOGrid1.ShowData rs
End Sub

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconPerformingParameterDrivenStoredProcedure.asp (1 of 2) [11/17/2002 11:20:24 PM]


Welcome to the MSDN Library

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconPerformingParameterDrivenStoredProcedure.asp (2 of 2) [11/17/2002 11:20:24 PM]


Performing a Stored Procedure That Returns Multiple Resultsets

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > Advanced RDO/ADO Data Access Scenarios

Visual Basic Concepts

Running a Stored Procedure That Returns Multiple Resultsets

See Also

RDO

This example illustrates how to perform a query that returns more than one resultset. It’s common for a stored procedure to return more than a single set of rows or a resultset that contains
results from an action query. As a result, your code must deal with each of the resultsets individually, or else you won’t be able to use the product of your query. In RDO, you use the MoreResults
method to step through the resultsets one at a time. Each call to MoreResults closes the current resultset and moves to the next (if there is one).

Private Sub MultipleRSButton_Click()


sql = "Select * from Authors Where year_born is not null; " _
& "Select * from Authors where year_born is null"
Set rs = cn.OpenResultset(sql)
rdoGrid1.ShowData rs

i = MsgBox("Ready for next results?", vbYesNoCancel)


If i = vbYes Then
If rs.MoreResults Then
rdoGrid1.ShowData rs
End If
End If
End Sub

ADO

The following code illustrates how to handle SPs that return multiple resultsets in ADO. ADO’s approach is different from the RDO approach in that ADO uses the NextRecordset method in which
you assign the next recordset in the batch to an ADO Recordset object. The next recordset read doesn't overwrite the first one, as it does in RDO. ADO also allows for multiple recordsets, if the
data provider supports it.

Private Sub MultipleRSButton_Click()


Dim rs As New ADODB.Recordset
sql = "Select * from Authors Where year_born is not null; " _
& "Select * from Authors where year_born is null"
rs.Open sql, cn
Do
i = MsgBox("Ready for results?", vbYesNoCancel)
If i = vbYes Then
ADOGrid1.ShowData rs
Set rs = rs.NextRecordset
End If
Loop Until rs.State = adStateClosed
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/...ProcedureThatReturnsMultipleResultsets.asp?frame=true [11/17/2002 11:20:28 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > Advanced RDO/ADO Data Access Scenarios

MSDN Library GO
Advanced Search Visual Basic Concepts

Running a Stored Procedure That Returns Multiple Resultsets

See Also

Up One Level RDO

Executing a Parameter Query


This example illustrates how to perform a query that returns more than one resultset. It’s common for a stored procedure to return more than a single set of rows or a resultset that contains
Performing a Parameter-Driven Stored Procedure results from an action query. As a result, your code must deal with each of the resultsets individually, or else you won’t be able to use the product of your query. In RDO, you use the
MoreResults method to step through the resultsets one at a time. Each call to MoreResults closes the current resultset and moves to the next (if there is one).
Running a Stored Procedure That Returns Multiple Resultsets
Performing an Action Query
Private Sub MultipleRSButton_Click()
Running an Optimistic Batch Query sql = "Select * from Authors Where year_born is not null; " _
& "Select * from Authors where year_born is null"
Set rs = cn.OpenResultset(sql)
rdoGrid1.ShowData rs

i = MsgBox("Ready for next results?", vbYesNoCancel)


If i = vbYes Then
If rs.MoreResults Then
rdoGrid1.ShowData rs
End If
End If
End Sub

ADO

The following code illustrates how to handle SPs that return multiple resultsets in ADO. ADO’s approach is different from the RDO approach in that ADO uses the NextRecordset method in
which you assign the next recordset in the batch to an ADO Recordset object. The next recordset read doesn't overwrite the first one, as it does in RDO. ADO also allows for multiple
recordsets, if the data provider supports it.

Private Sub MultipleRSButton_Click()


Dim rs As New ADODB.Recordset
sql = "Select * from Authors Where year_born is not null; " _
& "Select * from Authors where year_born is null"
rs.Open sql, cn
Do
i = MsgBox("Ready for results?", vbYesNoCancel)
If i = vbYes Then
ADOGrid1.ShowData rs
Set rs = rs.NextRecordset
End If
Loop Until rs.State = adStateClosed
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconPerformingStoredProcedureThatReturnsMultipleResultsets.asp [11/17/2002 11:20:29 PM]


Performing an Action Query

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > Advanced RDO/ADO Data Access Scenarios

Visual Basic Concepts

Performing an Action Query

See Also

RDO

In case your application needs to manipulate tables directly, or perform a maintenance operation (like SQL Server’s DBCC functions), you can use the Execute method to run the query directly. In
this case, you don’t need ODBC or SQL Server to create a temporary SP to run the query as it’s only being done once. (If this were a regular operation, it would be more efficient to create an SP to
do it.) Note that you can use the RowsAffected property to find out the number of rows affected by this query.

Private Sub ExecuteButton_Click()


sql = "Begin Transaction " _
& " Update Authors " _
& " set Year_Born = 1900 where year_born is null" _
& " rollback transaction"
Screen.MousePointer = vbHourglass
cn.Execute sql, rdExecDirect
ShowRows = cn.RowsAffected
Screen.MousePointer = vbDefault
End Sub

ADO

When you need to perform an action query, you can take advantage of the Execute method in ADO. In this case, you have to set a few more properties than you do in RDO, but these properties
improve data access performance. This is because ADO doesn’t have to poll the server to determine what to do, or how to handle the query. Note that the new output argument for the Execute
method returns the number of rows affected. Generally, you don’t see Visual Basic using arguments passed back to the application; just arguments passed to the object interface.

Private Sub ExecuteButton_Click()


Dim Qy As New ADODB.Command
Dim Rows As Long
sql = "Begin Transaction " _
& " Update Authors " _
& " set Year_Born = 1900 where year_born is null" _
& " rollback transaction"
Qy.ActiveConnection = cn
Qy.CommandText = sql
Qy.CommandType = adCmdText
Qy.Execute Rows
MsgBox Rows & " rows would have been affected", vbInformation
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconPerformingActionQuery.asp?frame=true [11/17/2002 11:20:34 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > Advanced RDO/ADO Data Access Scenarios

MSDN Library GO
Advanced Search Visual Basic Concepts

Performing an Action Query

See Also

Up One Level RDO

Executing a Parameter Query


In case your application needs to manipulate tables directly, or perform a maintenance operation (like SQL Server’s DBCC functions), you can use the Execute method to run the query
Performing a Parameter-Driven Stored Procedure directly. In this case, you don’t need ODBC or SQL Server to create a temporary SP to run the query as it’s only being done once. (If this were a regular operation, it would be more efficient to
create an SP to do it.) Note that you can use the RowsAffected property to find out the number of rows affected by this query.
Running a Stored Procedure That Returns Multiple Resultsets
Performing an Action Query
Private Sub ExecuteButton_Click()
Running an Optimistic Batch Query sql = "Begin Transaction " _
& " Update Authors " _
& " set Year_Born = 1900 where year_born is null" _
& " rollback transaction"
Screen.MousePointer = vbHourglass
cn.Execute sql, rdExecDirect
ShowRows = cn.RowsAffected
Screen.MousePointer = vbDefault
End Sub

ADO

When you need to perform an action query, you can take advantage of the Execute method in ADO. In this case, you have to set a few more properties than you do in RDO, but these
properties improve data access performance. This is because ADO doesn’t have to poll the server to determine what to do, or how to handle the query. Note that the new output argument for
the Execute method returns the number of rows affected. Generally, you don’t see Visual Basic using arguments passed back to the application; just arguments passed to the object interface.

Private Sub ExecuteButton_Click()


Dim Qy As New ADODB.Command
Dim Rows As Long
sql = "Begin Transaction " _
& " Update Authors " _
& " set Year_Born = 1900 where year_born is null" _
& " rollback transaction"
Qy.ActiveConnection = cn
Qy.CommandText = sql
Qy.CommandType = adCmdText
Qy.Execute Rows
MsgBox Rows & " rows would have been affected", vbInformation
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconPerformingActionQuery.asp [11/17/2002 11:20:36 PM]


Performing an Optimistic Batch Query

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > Advanced RDO/ADO Data Access Scenarios

Visual Basic Concepts

Running an Optimistic Batch Query

See Also

RDO

The following code demonstrates a query that can be used to drive a subsequent "optimistic batch update" operation. In this case, you fetch a resultset using the ClientBatch cursor library and
save the bookmarks for each row fetched. When the user chooses a row in the grid (where the rows are displayed), the code prompts the user for a new value and writes it to the resultset. The
changes are not made to the data, however, until you perform the BatchUpdate method.

Private Sub BatchOpsButton_Click()


Dim rs As rdoResultset
sql = "Select * from Authors where year_born is null"
rdoEnvironment.CursorDriver = rdUseClientBatch
cnB.QueryTimeout = 45
Set rs = cnB.OpenResultset(sql, rdOpenStatic, rdConcurBatch)
rs.MoveLast: rs.MoveFirst
ReDim bms(rs.RowCount + 1) As Variant
Do Until rs.EOF
bms(i) = rs.Bookmark
i = i + 1
rs.MoveNext
Loop
rs.MoveFirst
rdoGrid1.ShowData rs
End Sub

Performing an Update Operation Based on User Input


The following code demonstrates how to gather user input (in this case, author age), and then use this information to update the database in a batch update operation:

Private Sub rdoGrid1_Click()


Dim rs As rdoResultset
Dim NewValue As Integer
NewValue = InputBox("Enter new age -- 1900 to 1997", "Author Age", _
"1960")
rs.Bookmark = bms(rdoGrid1.Row)
rs.Edit
rs!Year_Born = NewValue
rs.Update
Changes = Changes + 1
i = MsgBox("Commit all " & Changes & " changes?", vbYesNoCancel)
Select Case i
Case vbYes
rs.BatchUpdate
Changes = 0
Case vbNo
Exit Sub
Case vbCancel
Changes = 0
i = MsgBox("Cancel just this change (Yes) or all " & Changes & _
" made so far (No)?", vbYesNo)
If i = vbYes Then
rs.CancelBatch (True)
Else
rs.CancelBatch
End If
End Select
End Sub

ADO

In this batch operation, note that the routine used to change the chosen row in the R/W resultset doesn't require starting an "Edit" session. To achieve the same effect as the previous RDO
example, simply change the contents of a field and use the Update method to make the changes to the database.

Private Sub BatchOpsButton_Click()


sql = "Select * from Authors where year_born is null"
rs.Open sql, cnB, adOpenStatic, adLockBatchOptimistic
rs.MoveLast: rs.MoveFirst
ReDim bms(rs.RecordCount + 1) As Variant
Do Until rs.EOF
bms(i) = rs.Bookmark
i = i + 1
rs.MoveNext
Loop
rs.MoveFirst
ADOGrid1.ShowData rs
rs.Close
End Sub

http://msdn.microsoft.com/library/en-us/vbcon98/h...bconPerformingOptimisticBatchQuery.asp?frame=true (1 of 2) [11/17/2002 11:20:40 PM]


Performing an Optimistic Batch Query

Private Sub ADOGrid1_Click()


Dim NewValue As Integer
NewValue = InputBox("Enter new age -- 1900 to 1997", "Author Age", _
"1960")
rs.Bookmark = bms(ADOGrid1.Row)
rs!Year_Born = NewValue
rs.Update
Changes = Changes + 1
i = MsgBox("Commit all " & Changes & " changes?", vbYesNoCancel)
Select Case i
Case vbYes
rs.UpdateBatch
Changes = 0
Case vbNo
Exit Sub
Case vbCancel
Changes = 0
i = MsgBox("Cancel just this change (Yes) or all " & Changes & _
" made so far (No)?", vbYesNo)
If i = vbYes Then
rs.CancelBatch (True)
Else
rs.CancelBatch
End If
End Select
End Sub

Note In ADO2, you can use a batch filter to see rows that conflicted with an update rather than iterating through an array of conflicted rows, as was required in RDO2.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/h...bconPerformingOptimisticBatchQuery.asp?frame=true (2 of 2) [11/17/2002 11:20:40 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO > Advanced RDO/ADO Data Access Scenarios

MSDN Library GO
Advanced Search Visual Basic Concepts

Running an Optimistic Batch Query

See Also

Up One Level RDO

Executing a Parameter Query


The following code demonstrates a query that can be used to drive a subsequent "optimistic batch update" operation. In this case, you fetch a resultset using the ClientBatch cursor library and
Performing a Parameter-Driven Stored Procedure save the bookmarks for each row fetched. When the user chooses a row in the grid (where the rows are displayed), the code prompts the user for a new value and writes it to the resultset.
The changes are not made to the data, however, until you perform the BatchUpdate method.
Running a Stored Procedure That Returns Multiple Resultsets
Performing an Action Query
Private Sub BatchOpsButton_Click()
Running an Optimistic Batch Query Dim rs As rdoResultset
sql = "Select * from Authors where year_born is null"
rdoEnvironment.CursorDriver = rdUseClientBatch
cnB.QueryTimeout = 45
Set rs = cnB.OpenResultset(sql, rdOpenStatic, rdConcurBatch)
rs.MoveLast: rs.MoveFirst
ReDim bms(rs.RowCount + 1) As Variant
Do Until rs.EOF
bms(i) = rs.Bookmark
i = i + 1
rs.MoveNext
Loop
rs.MoveFirst
rdoGrid1.ShowData rs
End Sub

Performing an Update Operation Based on User Input


The following code demonstrates how to gather user input (in this case, author age), and then use this information to update the database in a batch update operation:

Private Sub rdoGrid1_Click()


Dim rs As rdoResultset
Dim NewValue As Integer
NewValue = InputBox("Enter new age -- 1900 to 1997", "Author Age", _
"1960")
rs.Bookmark = bms(rdoGrid1.Row)
rs.Edit
rs!Year_Born = NewValue
rs.Update
Changes = Changes + 1
i = MsgBox("Commit all " & Changes & " changes?", vbYesNoCancel)
Select Case i
Case vbYes
rs.BatchUpdate
Changes = 0
Case vbNo
Exit Sub
Case vbCancel
Changes = 0
i = MsgBox("Cancel just this change (Yes) or all " & Changes & _
" made so far (No)?", vbYesNo)
If i = vbYes Then
rs.CancelBatch (True)
Else
rs.CancelBatch
End If
End Select
End Sub

ADO

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconPerformingOptimisticBatchQuery.asp (1 of 2) [11/17/2002 11:20:42 PM]


Welcome to the MSDN Library
In this batch operation, note that the routine used to change the chosen row in the R/W resultset doesn't require starting an "Edit" session. To achieve the same effect as the previous RDO
example, simply change the contents of a field and use the Update method to make the changes to the database.

Private Sub BatchOpsButton_Click()


sql = "Select * from Authors where year_born is null"
rs.Open sql, cnB, adOpenStatic, adLockBatchOptimistic
rs.MoveLast: rs.MoveFirst
ReDim bms(rs.RecordCount + 1) As Variant
Do Until rs.EOF
bms(i) = rs.Bookmark
i = i + 1
rs.MoveNext
Loop
rs.MoveFirst
ADOGrid1.ShowData rs
rs.Close
End Sub

Private Sub ADOGrid1_Click()


Dim NewValue As Integer
NewValue = InputBox("Enter new age -- 1900 to 1997", "Author Age", _
"1960")
rs.Bookmark = bms(ADOGrid1.Row)
rs!Year_Born = NewValue
rs.Update
Changes = Changes + 1
i = MsgBox("Commit all " & Changes & " changes?", vbYesNoCancel)
Select Case i
Case vbYes
rs.UpdateBatch
Changes = 0
Case vbNo
Exit Sub
Case vbCancel
Changes = 0
i = MsgBox("Cancel just this change (Yes) or all " & Changes & _
" made so far (No)?", vbYesNo)
If i = vbYes Then
rs.CancelBatch (True)
Else
rs.CancelBatch
End If
End Select
End Sub

Note In ADO2, you can use a batch filter to see rows that conflicted with an update rather than iterating through an array of conflicted rows, as was required in RDO2.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconPerformingOptimisticBatchQuery.asp (2 of 2) [11/17/2002 11:20:42 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)

MSDN Library GO
Advanced Search Visual Basic Concepts

Using Data Access Objects with Remote Databases

See Also

Up One Level Data Access Objects (DAO) can be used either with the Microsoft Jet database engine or, using the ODBCDirect option, without it. This chapter discusses design and implementation issues that
arise when using the Data Access Objects (DAO) to access remote databases.
DAO Remote Data Access Using Jet
Managing DAO ODBC Users You may find the Jet Database Engine Programmer's Guide and Hitchhiker's Guide to Visual Basic and SQL Server (both published by Microsoft Press) useful sources of information on using
Managing DAO Network Traffic DAO to access ODBC data sources using Jet.

Managing DAO ODBC Connections with Jet


Choosing a DAO Query Processor with Jet Topics

Building DAO Cursors with Jet


DAO Remote Data Access Using Jet

Using DAO to Share Remote Data


Handling Remote DAO Messages and Errors Provides a brief overview of remote data access with DAO using the Jet engine.

Remote Data Access Using DAO and ODBCDirect

Managing DAO ODBC Users

Briefly summarizes issues such as capacity, security, and maintenance.

Managing DAO Network Traffic

Outlines designing and debugging with network capacity in mind.

Managing DAO ODBC Connections with Jet

Outlines issues relevant to opening a connection to an ODBC data source with the Jet engine.

Choosing a DAO Query Processor for Use with Jet

Overviews issues relevant to performing queries on remote databases with the Jet engine.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingDataAccessObjectsWithRemoteDatabases.asp (1 of 2) [11/17/2002 11:21:02 PM]


Welcome to the MSDN Library

Building DAO Cursors with Jet

Lists and describes cursors supported by the Jet engine.

Using DAO to Share Remote Data

Briefly describes issues relevant to sharing a database among users and applications.

Handling Remote DAO Messages and Errors

Outlines issues involved in handling errors during DAO remote database access.

Remote Data Access Using DAO and ODBCDirect

Briefly describes the ODBCDirect option, which maps DAO to Remote Data Objects.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingDataAccessObjectsWithRemoteDatabases.asp (2 of 2) [11/17/2002 11:21:02 PM]


DAO Remote Data Access Using Jet

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

Visual Basic Concepts

DAO Remote Data Access Using Jet

See Also

This section discusses DAO functionality when it is connected to the Jet engine. The Microsoft Jet database engine is a stand-alone database management system that is capable of both processing
queries and routing queries to remote servers as needed. Accessing Jet through DAO adds to Microsoft Visual Basic’s ease of development by providing an object-oriented development paradigm
and accessibility to data-aware bound controls.

By using the Data control, DAO, or Microsoft Access, you can create code that is virtually database-independent, because Jet automatically performs all syntax and data manipulation translations
for you. For example, you can write an application that accesses different types of data sources without making reference to specific remote server features. These data sources could be Open
Database Connectivity (ODBC) databases, such as Microsoft SQL Server; Index Sequential Access Method (ISAM) databases, such as Microsoft FoxPro, Paradox, or dBASE; or other Jet databases.

Unlike most stand-alone database engines, Jet can perform heterogeneous joins across several dissimilar databases. If you are working with departmental data stored in ISAM format, and need to
merge it with data on a centralized server, this is an essential feature.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconRemoteDataAccessUsingJet.asp?frame=true [11/17/2002 11:21:05 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

MSDN Library GO
Advanced Search Visual Basic Concepts

DAO Remote Data Access Using Jet

See Also

Up One Level This section discusses DAO functionality when it is connected to the Jet engine. The Microsoft Jet database engine is a stand-alone database management system that is capable of both
processing queries and routing queries to remote servers as needed. Accessing Jet through DAO adds to Microsoft Visual Basic’s ease of development by providing an object-oriented
DAO Remote Data Access Using Jet development paradigm and accessibility to data-aware bound controls.

Managing DAO ODBC Users


Managing DAO Network Traffic By using the Data control, DAO, or Microsoft Access, you can create code that is virtually database-independent, because Jet automatically performs all syntax and data manipulation
translations for you. For example, you can write an application that accesses different types of data sources without making reference to specific remote server features. These data sources
Managing DAO ODBC Connections with Jet could be Open Database Connectivity (ODBC) databases, such as Microsoft SQL Server; Index Sequential Access Method (ISAM) databases, such as Microsoft FoxPro, Paradox, or dBASE; or
other Jet databases.
Choosing a DAO Query Processor with Jet
Building DAO Cursors with Jet Unlike most stand-alone database engines, Jet can perform heterogeneous joins across several dissimilar databases. If you are working with departmental data stored in ISAM format, and
Using DAO to Share Remote Data need to merge it with data on a centralized server, this is an essential feature.

Handling Remote DAO Messages and Errors


Remote Data Access Using DAO and ODBCDirect
Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRemoteDataAccessUsingJet.asp [11/17/2002 11:21:07 PM]


Managing DAO ODBC Users

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

Visual Basic Concepts

Managing DAO ODBC Users

See Also

Each instance of your database application uses some number of connections and data page (or row) locks on the server, and creates a measurable load on the network. Since each additional user
contends for many of the same resources, the number of users the system can support is directly proportional to the number of resources each instance of your application requires.

To reduce the number of locks, users should not be permitted to “sit” on unpopulated Recordset objects. The application should populate the recordset as quickly as possible using DAO, the Data
control, or one of the background population techniques.

Your design should also include management of user logon IDs and passwords. If your design uses a shared Jet (.mdb) database, you must also address Jet security systems.

Because all users must disconnect from Jet databases (that contain data) for periodic maintenance, you should include a way to notify users to disconnect from the shared Jet database or provide
a way to signal applications to disconnect automatically on their own. If the maintenance operations are executed during nonpeak hours, and applications automatically disconnect from the Jet
database after a length of idle time, maintenance programs can execute without disturbing uncompleted result sets or pending updates.

For More Information See “Managing DAO ODBC Connections With Jet” later in this chapter.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconManagingUsers.asp?frame=true [11/17/2002 11:21:14 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

MSDN Library GO
Advanced Search Visual Basic Concepts

Managing DAO ODBC Users

See Also

Up One Level Each instance of your database application uses some number of connections and data page (or row) locks on the server, and creates a measurable load on the network. Since each additional
user contends for many of the same resources, the number of users the system can support is directly proportional to the number of resources each instance of your application requires.
DAO Remote Data Access Using Jet
Managing DAO ODBC Users To reduce the number of locks, users should not be permitted to “sit” on unpopulated Recordset objects. The application should populate the recordset as quickly as possible using DAO, the
Managing DAO Network Traffic Data control, or one of the background population techniques.

Managing DAO ODBC Connections with Jet


Choosing a DAO Query Processor with Jet Your design should also include management of user logon IDs and passwords. If your design uses a shared Jet (.mdb) database, you must also address Jet security systems.

Building DAO Cursors with Jet


Using DAO to Share Remote Data Because all users must disconnect from Jet databases (that contain data) for periodic maintenance, you should include a way to notify users to disconnect from the shared Jet database or
provide a way to signal applications to disconnect automatically on their own. If the maintenance operations are executed during nonpeak hours, and applications automatically disconnect from
Handling Remote DAO Messages and Errors the Jet database after a length of idle time, maintenance programs can execute without disturbing uncompleted result sets or pending updates.

Remote Data Access Using DAO and ODBCDirect


For More Information See “Managing DAO ODBC Connections With Jet” later in this chapter.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconManagingUsers.asp [11/17/2002 11:21:15 PM]


Managing DAO Network Traffic

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

Visual Basic Concepts

Managing DAO Network Traffic

See Also

When using DAO with the Jet engine, a primary consideration is the amount of data that your network is required to carry. This is especially true if your design includes a shared Jet database that
contains local, unattached data. In this case, the network will carry all disk I/O traffic as multiple users compete for shared data pages. If the shared database is simply a repository for one or
more attached tables, in most cases only the query results need to be transmitted over the network.

Your application can control network traffic indirectly, through judicious use of Recordset object size and choice of query processor. In many cases, the Jet query processor can create Recordset
objects with comparatively little network traffic. However, some designs may not accommodate its use, and may consequently create more network traffic than would occur with other
programming models. By tuning the SQL query passed to the Jet query processor, you can often make better use of its power while improving network performance.

When accessing attached tables with the Jet engine, only the linkage information and the results of the query need to be transmitted over the network. If, however, the query processor is forced
to download part or all of a remote table, network load increases dramatically.

Using a wide area network (WAN) with a Jet database is possible, and with careful error management, WAN applications can be implemented with a degree of security. Your design should,
however, take additional precautions and include extremely robust error management that anticipates the loss of network access to the remote server and often dramatically longer response
times. Since WAN networks can be significantly slower than conventional local area networks, special care should be given to the amount of network traffic generated and DAO timeout values.
Examine the SQL trace logs for a better understanding of the number and complexity of the queries generated to remote ODBC servers. It is always good design practice to use more robust error
handling for all network operations regardless of the topology.

Enabling Trace Logs

One of the most helpful debugging and tuning tools you have at your disposal is the ability of the ODBC Driver Manager to log all ODBC operations to an external file. You can enable this file using
the ODBCDirect LogMessages property or by selecting the associated option in the Windows control panel ODBC Administration dialog. Be sure to turn off logging before your application goes into
production, as the logging process can significantly impact performance.

Another option available to Microsoft SQL Server developers is the new SQLTrace utility that can let developers interactively view the queries submitted by all applications against a SQL Server.
Once started, the SQLTrace utility exposes a window that displays each query or other operational request made.

For More Information See “Choosing a DAO Query Processor for Use with Jet” and “Managing DAO ODBC Connections with Jet.”

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconManagingNetworkTraffic.asp?frame=true [11/17/2002 11:21:20 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

MSDN Library GO
Advanced Search Visual Basic Concepts

Managing DAO Network Traffic

See Also

Up One Level When using DAO with the Jet engine, a primary consideration is the amount of data that your network is required to carry. This is especially true if your design includes a shared Jet database
that contains local, unattached data. In this case, the network will carry all disk I/O traffic as multiple users compete for shared data pages. If the shared database is simply a repository for
DAO Remote Data Access Using Jet one or more attached tables, in most cases only the query results need to be transmitted over the network.

Managing DAO ODBC Users


Managing DAO Network Traffic Your application can control network traffic indirectly, through judicious use of Recordset object size and choice of query processor. In many cases, the Jet query processor can create
Recordset objects with comparatively little network traffic. However, some designs may not accommodate its use, and may consequently create more network traffic than would occur with
Managing DAO ODBC Connections with Jet other programming models. By tuning the SQL query passed to the Jet query processor, you can often make better use of its power while improving network performance.

Choosing a DAO Query Processor with Jet


Building DAO Cursors with Jet When accessing attached tables with the Jet engine, only the linkage information and the results of the query need to be transmitted over the network. If, however, the query processor is
forced to download part or all of a remote table, network load increases dramatically.
Using DAO to Share Remote Data
Handling Remote DAO Messages and Errors Using a wide area network (WAN) with a Jet database is possible, and with careful error management, WAN applications can be implemented with a degree of security. Your design should,
Remote Data Access Using DAO and ODBCDirect however, take additional precautions and include extremely robust error management that anticipates the loss of network access to the remote server and often dramatically longer response
times. Since WAN networks can be significantly slower than conventional local area networks, special care should be given to the amount of network traffic generated and DAO timeout values.
Examine the SQL trace logs for a better understanding of the number and complexity of the queries generated to remote ODBC servers. It is always good design practice to use more robust
error handling for all network operations regardless of the topology.

Enabling Trace Logs

One of the most helpful debugging and tuning tools you have at your disposal is the ability of the ODBC Driver Manager to log all ODBC operations to an external file. You can enable this file
using the ODBCDirect LogMessages property or by selecting the associated option in the Windows control panel ODBC Administration dialog. Be sure to turn off logging before your application
goes into production, as the logging process can significantly impact performance.

Another option available to Microsoft SQL Server developers is the new SQLTrace utility that can let developers interactively view the queries submitted by all applications against a SQL Server.
Once started, the SQLTrace utility exposes a window that displays each query or other operational request made.

For More Information See “Choosing a DAO Query Processor for Use with Jet” and “Managing DAO ODBC Connections with Jet.”

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconManagingNetworkTraffic.asp [11/17/2002 11:21:23 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

MSDN Library GO
Advanced Search Visual Basic Concepts

Managing DAO ODBC Connections with Jet

See Also

Up One Level When you access an ODBC database through DAO or the Data control using Jet, the Microsoft Jet database engine and its connection management routines are automatically invoked. Jet will
make every attempt to open as few connections as possible and share connections whenever possible.
Managing DAO Data Source Name Entries
Establishing DAO ODBC Connections with Jet Generally, the Jet database engine attempts to share or cache any connections established by your application. As a rule of thumb, if the Data Source Name (DSN) you request is referenced by
Caching DAO ODBC Connections with Jet more than one OpenDatabase call, then DAO and Jet attempt to re-use that connection. That is, if you already have a connection open to a specific DSN, Jet will not attempt to open another if
it thinks it can share the existing connection. When you use the Close method on a DAO Database object, Jet does not close the connection immediately if it is the last connection to the specific
Closing DAO ODBC Connections with Jet DSN — it is cached in case you try to open the connection again.

Opening Connections

There are two primary ways to access remote ODBC data sources using DAO and Jet. Both techniques involve the OpenDatabase method against:

● An ODBC data source. In this case, the connect string argument of the OpenDatabase method specifies a DSN that points to the ODBC data source.

● A Jet database containing linked (attached) ODBC data source tables or views. In this case, the OpenDatabase dbName argument points to the path of a Jet .mdb database. The Jet database contains the DSN and, optionally, the user name and password.

Each technique has its advantages and disadvantages. However, using the OpenDatabase method against an ODBC DSN requires that Jet download a significant amount of descriptive
information, as data definition language (DDL), about the target database. Because this information is not cached, this DDL fetch operation must be repeated each time the Database object is
opened. This is one reason why Jet attempts to cache connections — so this process does not have to be repeated.

The process of attaching or linking to a table from an ODBC data source caches the DDL information in the Jet database, so it is not necessary to perform the DDL query when the connection is
established or the database is opened. This can dramatically improve performance when opening a connection and creating a DAO Database object.

For More Information For details about connection strategies, see "Caching DAO ODBC Connections with Jet" in this chapter.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconManagingJetODBCConnections.asp [11/17/2002 11:21:29 PM]


Managing DAO Data Source Name Entries

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Managing DAO ODBC Connections with Jet

Visual Basic Concepts

Managing DAO Data Source Name Entries

See Also

Generally, an ODBC connection requires a Data Source Name (DSN) entry. Depending on the operating system, these entries are either kept in the ODBC.ini file (16-bit systems) or in the system
registry (32-bit systems). You should not attempt to change these entries manually. Instead, use the Windows Control Panel ODBC Administration applet or the RegisterDatabase method.

Note When using the DAO/Jet model, ODBCDirect, Remote Data Objects, or the ODBC API, it is not always necessary to create or reference a registered DSN if enough information about the
remote server is provided in the connect string.

Setting the Default Database

Your code should ensure that the correct default database is set during the connection process. The user may specify a user ID that does not have permission to access the database your
application expects to use, or uses a different default database. The default database can be established by:

● Including the default database name in the DSN entry.

● Including the DATABASE= argument in the connect string.

● Establishing a default database on the server based on the user name.

● Submitting an action query that changes the default database once the connection is open.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconDataSourceNameEntries.asp?frame=true [11/17/2002 11:21:32 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Managing DAO ODBC Connections with Jet

MSDN Library GO
Advanced Search Visual Basic Concepts

Managing DAO Data Source Name Entries

See Also

Up One Level Generally, an ODBC connection requires a Data Source Name (DSN) entry. Depending on the operating system, these entries are either kept in the ODBC.ini file (16-bit systems) or in the
system registry (32-bit systems). You should not attempt to change these entries manually. Instead, use the Windows Control Panel ODBC Administration applet or the RegisterDatabase
Managing DAO Data Source Name Entries method.

Establishing DAO ODBC Connections with Jet


Caching DAO ODBC Connections with Jet Note When using the DAO/Jet model, ODBCDirect, Remote Data Objects, or the ODBC API, it is not always necessary to create or reference a registered DSN if enough information about the
remote server is provided in the connect string.
Closing DAO ODBC Connections with Jet
Setting the Default Database

Your code should ensure that the correct default database is set during the connection process. The user may specify a user ID that does not have permission to access the database your
application expects to use, or uses a different default database. The default database can be established by:

● Including the default database name in the DSN entry.

● Including the DATABASE= argument in the connect string.

● Establishing a default database on the server based on the user name.

● Submitting an action query that changes the default database once the connection is open.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconDataSourceNameEntries.asp [11/17/2002 11:21:34 PM]


Establishing DAO ODBC Connections with Jet

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Managing DAO ODBC Connections with Jet

Visual Basic Concepts

Establishing DAO ODBC Connections with Jet

See Also

Jet requires at least one connection when fetching data from a remote data source. If you indicate that the result set is to be updated, Jet attempts to open an additional connection unless an
existing connection can be used. That is, one connection is used to populate the result set, and another to update it. However, once the result set is fully populated — as when you use the
MoveLast method — the first connection can be closed or returned to the connection cache.

Providing User ID and Password

To gain access to a remote ODBC data source, you usually have to provide a valid user ID and password combination. These values can be provided in the Connect property of the Data control or
in the connect string that is supplied as an argument to the OpenDatabase method. If these values are not supplied, the ODBC Driver Manager exposes a dialog to collect the user name,
password, and other missing information needed to establish the connection. There is no way to disable this dialog with DAO and Jet. However, by using the ODBCDirect or RDO prompt
arguments, this dialog can be disabled and your code can intercept a trappable error.

Opening Connections Directly

Jet follows these guidelines when managing connections to Microsoft SQL Server:

● When using the OpenDatabase method, Jet opens a new connection, or attempts to re-use an existing connection if an identical DSN exists in the cache. The connection remains open after the Database object is closed (in anticipation of later use), unless there is
already a cached connection to that server available. Only one connection for each DSN remains open in the cache.

● When you open a connection directly using the OpenDatabase method, the DAO/Jet model is forced to query the database to determine the name of each available table there. This information is cached in the Database object and exists (does not have to be
refetched) as long as the Database object remains instantiated.

● With OpenRecordset, Jet tries to share an existing connection, reuse a cached connection, or, failing both of those, opens a new connection to the server and executes a query based on the source argument (or the SQL property of a QueryDef object). As soon as a
MoveNext method is executed, Jet fetches the first 100 rows. If this does not complete the query, an additional connection is opened to support updates. The first connection must remain open until the recordset is fully populated or closed to support updates.

Opening Connections Indirectly

It usually more efficient to open connections to a remote data source by having Jet perform the operation. This is accomplished by simply opening a Jet database that contains linkages to remote
database tables or views. When you access these attached (linked) objects, Jet establishes the connection using cached connection information that you provided when creating the attachments.
However, if Jet is unable to complete the connection for whatever reason, the ODBC driver manager exposes a series of dialogs to attempt to collect logon and DSN information so the connection
can be established. Using DAO with Jet, there is no way to disable these dialogs.

Another alternative is to provide the needed connection information to DAO and Jet by setting the Connect property on an open DAO/Jet Database object. Using this technique, you can then use
SQL PassThrough queries just as if you had opened the connection directly.

For More Information For code examples illustrating the OpenDatabase and OpenRecordset methods, see “OpenDatabase” and “OpenRecordset” in the Language Reference".

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconEstablishingJetODBCConnections.asp?frame=true [11/17/2002 11:21:39 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Managing DAO ODBC Connections with Jet

MSDN Library GO
Advanced Search Visual Basic Concepts

Establishing DAO ODBC Connections with Jet

See Also

Up One Level Jet requires at least one connection when fetching data from a remote data source. If you indicate that the result set is to be updated, Jet attempts to open an additional connection unless an
existing connection can be used. That is, one connection is used to populate the result set, and another to update it. However, once the result set is fully populated — as when you use the
Managing DAO Data Source Name Entries MoveLast method — the first connection can be closed or returned to the connection cache.

Establishing DAO ODBC Connections with Jet


Caching DAO ODBC Connections with Jet Providing User ID and Password

Closing DAO ODBC Connections with Jet


To gain access to a remote ODBC data source, you usually have to provide a valid user ID and password combination. These values can be provided in the Connect property of the Data control
or in the connect string that is supplied as an argument to the OpenDatabase method. If these values are not supplied, the ODBC Driver Manager exposes a dialog to collect the user name,
password, and other missing information needed to establish the connection. There is no way to disable this dialog with DAO and Jet. However, by using the ODBCDirect or RDO prompt
arguments, this dialog can be disabled and your code can intercept a trappable error.

Opening Connections Directly

Jet follows these guidelines when managing connections to Microsoft SQL Server:

● When using the OpenDatabase method, Jet opens a new connection, or attempts to re-use an existing connection if an identical DSN exists in the cache. The connection remains open after the Database object is closed (in anticipation of later use), unless
there is already a cached connection to that server available. Only one connection for each DSN remains open in the cache.

● When you open a connection directly using the OpenDatabase method, the DAO/Jet model is forced to query the database to determine the name of each available table there. This information is cached in the Database object and exists (does not have to be
refetched) as long as the Database object remains instantiated.

● With OpenRecordset, Jet tries to share an existing connection, reuse a cached connection, or, failing both of those, opens a new connection to the server and executes a query based on the source argument (or the SQL property of a QueryDef object). As
soon as a MoveNext method is executed, Jet fetches the first 100 rows. If this does not complete the query, an additional connection is opened to support updates. The first connection must remain open until the recordset is fully populated or closed to
support updates.

Opening Connections Indirectly

It usually more efficient to open connections to a remote data source by having Jet perform the operation. This is accomplished by simply opening a Jet database that contains linkages to
remote database tables or views. When you access these attached (linked) objects, Jet establishes the connection using cached connection information that you provided when creating the
attachments. However, if Jet is unable to complete the connection for whatever reason, the ODBC driver manager exposes a series of dialogs to attempt to collect logon and DSN information
so the connection can be established. Using DAO with Jet, there is no way to disable these dialogs.

Another alternative is to provide the needed connection information to DAO and Jet by setting the Connect property on an open DAO/Jet Database object. Using this technique, you can then
use SQL PassThrough queries just as if you had opened the connection directly.

For More Information For code examples illustrating the OpenDatabase and OpenRecordset methods, see “OpenDatabase” and “OpenRecordset” in the Language Reference".

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconEstablishingJetODBCConnections.asp [11/17/2002 11:21:41 PM]


Caching DAO ODBC Connections with Jet

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Managing DAO ODBC Connections with Jet

Visual Basic Concepts

Caching DAO ODBC Connections with Jet

See Also

A key part of connection management is that Jet caches either one or two connections, depending on the server. For servers such as Oracle, which allow pending results on a connection, Jet
caches one connection. For servers such as Microsoft SQL Server, which do not allow pending results on a connection, Jet caches two connections.

Note SQL Server's server-side cursors support multiple operations on a single connection as implemented with ODBCDirect and RDO. However, there is no support for server-side cursors with
Jet.

When Jet needs to open a connection, it first checks its internal connection cache. If there is a connection in the cache that uses the same DSN and database parameters, and there are no
uncompleted queries pending on the connection, it is reused. Back-end database systems that support pending results on a single connection may not need additional connections to perform
simultaneous read/write operations.

Note Jet caches the user ID and password along with the connection, so that you’re not repeatedly prompted. This means that if your application needs to log on to the server with a different
user ID and password, you will be unable to do so unless you force the closure of any existing connections.

Jet ages each connection based on elapsed time and its activity. After a configurable connection timeout period (which defaults to 10 minutes), Jet automatically closes and drops any dormant
connections. For a connection to be considered dormant, it must have no open Database or Workspace objects associated with it. Jet will not close connections if there are uncommitted
transactions, or queries with unfetched results. Since Jet automatically closes connections, this implies that Jet automatically re-opens connections as needed.

Note The ConnectionTimeout setting can be adjusted by accessing the Windows system registry.

If your application needs access to a connection that Jet has timed out and closed, the connection is automatically reopened. Assuming that the connection is re-established, this should not cause
a problem with your application.

In some cases, if a shared DSN is identical, queries against a second Database object might be blocked while Jet waits for the DSN to become available.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconConnectionCache.asp?frame=true [11/17/2002 11:21:47 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Managing DAO ODBC Connections with Jet

MSDN Library GO
Advanced Search Visual Basic Concepts

Caching DAO ODBC Connections with Jet

See Also

Up One Level A key part of connection management is that Jet caches either one or two connections, depending on the server. For servers such as Oracle, which allow pending results on a connection, Jet
caches one connection. For servers such as Microsoft SQL Server, which do not allow pending results on a connection, Jet caches two connections.
Managing DAO Data Source Name Entries
Establishing DAO ODBC Connections with Jet Note SQL Server's server-side cursors support multiple operations on a single connection as implemented with ODBCDirect and RDO. However, there is no support for server-side cursors
Caching DAO ODBC Connections with Jet with Jet.

Closing DAO ODBC Connections with Jet


When Jet needs to open a connection, it first checks its internal connection cache. If there is a connection in the cache that uses the same DSN and database parameters, and there are no
uncompleted queries pending on the connection, it is reused. Back-end database systems that support pending results on a single connection may not need additional connections to perform
simultaneous read/write operations.

Note Jet caches the user ID and password along with the connection, so that you’re not repeatedly prompted. This means that if your application needs to log on to the server with a different
user ID and password, you will be unable to do so unless you force the closure of any existing connections.

Jet ages each connection based on elapsed time and its activity. After a configurable connection timeout period (which defaults to 10 minutes), Jet automatically closes and drops any dormant
connections. For a connection to be considered dormant, it must have no open Database or Workspace objects associated with it. Jet will not close connections if there are uncommitted
transactions, or queries with unfetched results. Since Jet automatically closes connections, this implies that Jet automatically re-opens connections as needed.

Note The ConnectionTimeout setting can be adjusted by accessing the Windows system registry.

If your application needs access to a connection that Jet has timed out and closed, the connection is automatically reopened. Assuming that the connection is re-established, this should not
cause a problem with your application.

In some cases, if a shared DSN is identical, queries against a second Database object might be blocked while Jet waits for the DSN to become available.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconConnectionCache.asp [11/17/2002 11:21:49 PM]


Closing DAO ODBC Connections with Jet

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Managing DAO ODBC Connections with Jet

Visual Basic Concepts

Closing DAO ODBC Connections with Jet

See Also

When you close a Recordset or Database object, or when these objects are no longer in scope, the connections they use are released to the connection cache. For example, if you declare a
Recordset object in a procedure, and that procedure ends, the recordset is automatically closed and any connections needed to support it are released to the cache.

When your code visits the last record of a Recordset object, as when you execute the MoveLast method, the connection used to populate the recordset is released to the cache. A single connection
is maintained to perform updates or other action queries against all open Recordset objects.

When your code closes a Database object or the object loses scope, Jet closes the Database and any associated Recordset objects. Any connections associated with those objects are released to
the cache.

Each Data control functions like an OpenRecordset method. That is, each Data control creates one or two connections (depending on the size of the result set and the functionality of the server
being accessed) when they are initialized. Visual Basic automatically populates Recordset objects created by the Data control to release connections as quickly as possible. This happens during idle
time, and at a configurable rate determined by the MSysConf table settings. Generally, Jet maintains a single connection to perform updates, but until the result set associated with each Data
control is fully populated, a second connection must remain open to return the rows. When your code positions the recordset to the last row, as when you execute a MoveLast method, this extra
connection is no longer needed and is returned to the pool.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconClosingConnections.asp?frame=true [11/17/2002 11:21:53 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Managing DAO ODBC Connections with Jet

MSDN Library GO
Advanced Search Visual Basic Concepts

Closing DAO ODBC Connections with Jet

See Also

Up One Level When you close a Recordset or Database object, or when these objects are no longer in scope, the connections they use are released to the connection cache. For example, if you declare a
Recordset object in a procedure, and that procedure ends, the recordset is automatically closed and any connections needed to support it are released to the cache.
Managing DAO Data Source Name Entries
Establishing DAO ODBC Connections with Jet When your code visits the last record of a Recordset object, as when you execute the MoveLast method, the connection used to populate the recordset is released to the cache. A single
Caching DAO ODBC Connections with Jet connection is maintained to perform updates or other action queries against all open Recordset objects.

Closing DAO ODBC Connections with Jet


When your code closes a Database object or the object loses scope, Jet closes the Database and any associated Recordset objects. Any connections associated with those objects are released
to the cache.

Each Data control functions like an OpenRecordset method. That is, each Data control creates one or two connections (depending on the size of the result set and the functionality of the server
being accessed) when they are initialized. Visual Basic automatically populates Recordset objects created by the Data control to release connections as quickly as possible. This happens during
idle time, and at a configurable rate determined by the MSysConf table settings. Generally, Jet maintains a single connection to perform updates, but until the result set associated with each
Data control is fully populated, a second connection must remain open to return the rows. When your code positions the recordset to the last row, as when you execute a MoveLast method,
this extra connection is no longer needed and is returned to the pool.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconClosingConnections.asp [11/17/2002 11:21:55 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

MSDN Library GO
Advanced Search Visual Basic Concepts

Building DAO Cursors with Jet

See Also

Up One Level Whenever you execute a query that returns rows, you must decide which type of cursor is to be created to manage the result set. Cursors are simply a set of rows returned from the data
source that meet the criteria you specify in a SQL statement. The SQL statement indicates which table(s) and column(s) are to be returned and limits the rows based on criteria in a WHERE
Accessing SQL Views Using DAO clause.

Accessing Stored Procedures Using DAO


When using DAO and Jet to fetch information from the database, you must use the Recordset object to build a cursor. This can be accomplished using attached tables, QueryDef objects with
Connect strings and SQL queries, or a combination of the two.

The following terms are used when describing a cursor:

● Scrolling is the ability to position to a specific row of the result set using one or more DAO methods.

● Updatability indicates whether a cursor permits changes to the underlying database rows.

● Membership in the result set is determined by the SQL query. As you use the AddNew or Delete methods to add or remove rows or as others sharing the database make changes, the membership of a cursor might or might not reflect those changes.

● Static data values in static cursors have been copied to local memory where the cursor library makes no attempt to keep the data current. Keyset or dynamic cursors requery the database to fetch data from the database as you position over specific rows of
the result set.

The DAO/Jet model supports a variety of cursors against remote data sources including:

● Dynaset cursors are fully scrollable, updatable cursors with fixed membership and dynamic data values.

● Snapshot cursors are fully scrolling, read-only cursors with fixed membership and static data values.

● Forward-only cursors are nonscrolling, read-only cursors with fixed membership and static data values.

ODBCDirect adds Dynamic cursors to this list as implemented by RDO.

It always makes sense to create a cursor that has the least impact on your workstation and provides the best performance. The cursors created by DAO when using Jet can be expensive, in
that the default dynaset-type Recordset object cursor is read/write, is fully scrolling, and supports updatable heterogeneous joins. By choosing the DAO Jet forward-only, read-only cursor, you
can dramatically improve cursor performance. In contrast, the default ODBCDirect cursor is the most efficient, but offers fewer features because it defaults to a read-only forward-only
recordset.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconBuildingCursors.asp [11/17/2002 11:22:08 PM]


Accessing SQL Views Using DAO

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Building DAO Cursors with Jet

Visual Basic Concepts

Accessing SQL Views Using DAO

See Also

If the remote database only exposes SQL views, you can access this data by attaching those views to a Jet database and creating pseudo indexes to the view using a DAO action query. Although
not actually an index, a pseudo index allows Jet to create an updatable recordset on the view. You don’t need to create a pseudo index if you are not updating server data.

SQL views can also be accessed by DAO through ODBCDirect. In some cases these views are updatable using the indexes already available on the remote server.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconAccessingSQLViews.asp?frame=true [11/17/2002 11:22:15 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Building DAO Cursors with Jet

MSDN Library GO
Advanced Search Visual Basic Concepts

Accessing SQL Views Using DAO

See Also

Up One Level If the remote database only exposes SQL views, you can access this data by attaching those views to a Jet database and creating pseudo indexes to the view using a DAO action query.
Although not actually an index, a pseudo index allows Jet to create an updatable recordset on the view. You don’t need to create a pseudo index if you are not updating server data.
Accessing SQL Views Using DAO
Accessing Stored Procedures Using DAO SQL views can also be accessed by DAO through ODBCDirect. In some cases these views are updatable using the indexes already available on the remote server.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconAccessingSQLViews.asp [11/17/2002 11:22:18 PM]


Accessing Stored Procedures Using DAO

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Building DAO Cursors with Jet

Visual Basic Concepts

Accessing Stored Procedures Using DAO

See Also

In some environments, access to server data is limited to a set of server-based stored procedures. In this case, some or all data requests and updates are carried out through these stored
procedures — especially when you have no direct access to the remote tables. In such an environment, you must use SQL pass-through queries exclusively or use ODBCDirect if you choose to use
DAO. If your server forces all queries and updates to be executed through stored procedures, then you can use SQL pass-through queries to execute the UPDATE stored procedures as well as the
SELECT stored procedures. You can then base other Jet QueryDef objects on these queries as if they were attached tables.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconUsingStoredProcedures.asp?frame=true [11/17/2002 11:22:22 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases > Building DAO Cursors with Jet

MSDN Library GO
Advanced Search Visual Basic Concepts

Accessing Stored Procedures Using DAO

See Also

Up One Level In some environments, access to server data is limited to a set of server-based stored procedures. In this case, some or all data requests and updates are carried out through these stored
procedures — especially when you have no direct access to the remote tables. In such an environment, you must use SQL pass-through queries exclusively or use ODBCDirect if you choose to
Accessing SQL Views Using DAO use DAO. If your server forces all queries and updates to be executed through stored procedures, then you can use SQL pass-through queries to execute the UPDATE stored procedures as well
as the SELECT stored procedures. You can then base other Jet QueryDef objects on these queries as if they were attached tables.
Accessing Stored Procedures Using DAO

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingStoredProcedures.asp [11/17/2002 11:22:23 PM]


Using DAO to Share Remote Data

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

Visual Basic Concepts

Using DAO to Share Remote Data

See Also

In any client/server application, one of your primary design concerns will be how to best share the data resources. When using either the Jet or remote engine query processor, your design must
include code that deals with conflicts caused by instances of your database application and other applications trying to access the same database. Any design must include robust error handling to
deal with a variety of contingencies caused by conflicts that arise as multiple applications vie for the same server resources.

If your design calls for a centrally shared Jet database that includes attached tables, each client system must also contain DSNs that are compatible with your database. Since the DSN is
maintained on the client and only referenced by name in the shared database attachments, your setup routines must ensure the client DSN description is correct — and remains so — to eliminate
any chance that the user might change one or more parameters.

Although the remote database engine is responsible for managing its own page locks and resources, any application, including those that use the Jet query processor, can lock pages on the server
for indefinite periods of time.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconSharingData.asp?frame=true [11/17/2002 11:22:33 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

MSDN Library GO
Advanced Search Visual Basic Concepts

Using DAO to Share Remote Data

See Also

Up One Level In any client/server application, one of your primary design concerns will be how to best share the data resources. When using either the Jet or remote engine query processor, your design
must include code that deals with conflicts caused by instances of your database application and other applications trying to access the same database. Any design must include robust error
DAO Remote Data Access Using Jet handling to deal with a variety of contingencies caused by conflicts that arise as multiple applications vie for the same server resources.

Managing DAO ODBC Users


Managing DAO Network Traffic If your design calls for a centrally shared Jet database that includes attached tables, each client system must also contain DSNs that are compatible with your database. Since the DSN is
maintained on the client and only referenced by name in the shared database attachments, your setup routines must ensure the client DSN description is correct — and remains so — to
Managing DAO ODBC Connections with Jet eliminate any chance that the user might change one or more parameters.

Choosing a DAO Query Processor with Jet


Building DAO Cursors with Jet Although the remote database engine is responsible for managing its own page locks and resources, any application, including those that use the Jet query processor, can lock pages on the
server for indefinite periods of time.
Using DAO to Share Remote Data
Handling Remote DAO Messages and Errors
Remote Data Access Using DAO and ODBCDirect
Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconSharingData.asp [11/17/2002 11:22:36 PM]


Handling Remote DAO Messages and Errors

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

Visual Basic Concepts

Handling Remote DAO Messages and Errors

See Also

Remote server systems generate their own litany of errors and messages. The database itself may contain procedures that generate user-defined messages or errors. Once DAO and the Jet
database engine receive any error, regardless of the cause, the query that triggered the error is terminated. For those databases that use the SQL Server RaisError function to indicate warning-
level messages, this may be problematic.

When using QueryDef objects to execute SQL pass-through queries, other messages received from ODBC and the remote server can be trapped. For example, SQL Server SQL PRINT statements
generate a message that can be trapped by your code. To enable message trapping, your code must create a property named “LogMessages” for a specific QueryDef object, and set this property
to True. Once set, messages generated by the selected QueryDef are recorded in a Jet table.

Each SQL query that Jet or the remote query processor executes can generate one or more ODBC or other remote-engine errors. All of these errors are stored in the Errors collection, which is
accessible either during break mode or at run time. Documentation is available for some of these messages, especially those mapped by Jet to its own error numbers. Most ODBC operations will
generate a generic ODBC trappable error that is explained more fully in messages found in other members of the Errors collection.

For More Information See "Errors Collection" and "LogMessages Property" in the Language Reference.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconHandlingDAOMessagesErrors.asp?frame=true [11/17/2002 11:22:41 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

MSDN Library GO
Advanced Search Visual Basic Concepts

Handling Remote DAO Messages and Errors

See Also

Up One Level Remote server systems generate their own litany of errors and messages. The database itself may contain procedures that generate user-defined messages or errors. Once DAO and the Jet
database engine receive any error, regardless of the cause, the query that triggered the error is terminated. For those databases that use the SQL Server RaisError function to indicate warning-
DAO Remote Data Access Using Jet level messages, this may be problematic.

Managing DAO ODBC Users


Managing DAO Network Traffic When using QueryDef objects to execute SQL pass-through queries, other messages received from ODBC and the remote server can be trapped. For example, SQL Server SQL PRINT
statements generate a message that can be trapped by your code. To enable message trapping, your code must create a property named “LogMessages” for a specific QueryDef object, and set
Managing DAO ODBC Connections with Jet this property to True. Once set, messages generated by the selected QueryDef are recorded in a Jet table.

Choosing a DAO Query Processor with Jet


Building DAO Cursors with Jet Each SQL query that Jet or the remote query processor executes can generate one or more ODBC or other remote-engine errors. All of these errors are stored in the Errors collection, which is
accessible either during break mode or at run time. Documentation is available for some of these messages, especially those mapped by Jet to its own error numbers. Most ODBC operations
Using DAO to Share Remote Data will generate a generic ODBC trappable error that is explained more fully in messages found in other members of the Errors collection.

Handling Remote DAO Messages and Errors


Remote Data Access Using DAO and ODBCDirect For More Information See "Errors Collection" and "LogMessages Property" in the Language Reference.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconHandlingDAOMessagesErrors.asp [11/17/2002 11:22:43 PM]


Remote Data Access Using DAO and ODBCDirect

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

Visual Basic Concepts

Remote Data Access Using DAO and ODBCDirect

See Also

Visual Basic version offers an additional option that can be used with DAO to access remote database engines: ODBCDirect. This DAO option permits your application to choose the database engine
and interface used by DAO. Basically, you have two choices:

● The Microsoft Jet database engine. By default, DAO uses Jet to perform all data access operations.

● ODBCDirect. When this option is enabled, DAO loads the Remote Data Objects (RDO) 2.0 libraries and delegates all data access operations to the ODBC data source.

Basically, ODBCDirect maps each of the Data Access Objects to an equivalent Remote Data Object. While not all of the RDO functionality is implemented with ODBCDirect, this approach permits
you to leverage existing DAO-based applications using a familiar object model when accessing remote database systems.

For More Information Information about ODBCDirect’s relationship to RDO is also discussed throughout "Using Remote Data Objects and the Remote Data Control."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconUsingODBCDirect.asp?frame=true [11/17/2002 11:22:47 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases

MSDN Library GO
Advanced Search Visual Basic Concepts

Remote Data Access Using DAO and ODBCDirect

See Also

Up One Level Visual Basic version offers an additional option that can be used with DAO to access remote database engines: ODBCDirect. This DAO option permits your application to choose the database
engine and interface used by DAO. Basically, you have two choices:
DAO Remote Data Access Using Jet
Managing DAO ODBC Users ● The Microsoft Jet database engine. By default, DAO uses Jet to perform all data access operations.

Managing DAO Network Traffic ● ODBCDirect. When this option is enabled, DAO loads the Remote Data Objects (RDO) 2.0 libraries and delegates all data access operations to the ODBC data source.

Managing DAO ODBC Connections with Jet


Basically, ODBCDirect maps each of the Data Access Objects to an equivalent Remote Data Object. While not all of the RDO functionality is implemented with ODBCDirect, this approach
Choosing a DAO Query Processor with Jet permits you to leverage existing DAO-based applications using a familiar object model when accessing remote database systems.

Building DAO Cursors with Jet


Using DAO to Share Remote Data For More Information Information about ODBCDirect’s relationship to RDO is also discussed throughout "Using Remote Data Objects and the Remote Data Control."

Handling Remote DAO Messages and Errors


Remote Data Access Using DAO and ODBCDirect

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingODBCDirect.asp [11/17/2002 11:22:48 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)

MSDN Library GO
Advanced Search Visual Basic Concepts

Using Remote Data Objects and the RemoteData Control

See Also

Up One Level This chapter provides an overview of the features of the Remote Data Objects (RDO) programming model and the RemoteData control. The information in this chapter can help you make a
decision regarding which data access programming model to use in your client/server application.
Features of Remote Data Objects
Programming with Remote Data Objects Remote Data Objects implement a set of objects to deal with the special requirements of remote data access. RDO implements a thin code layer over the ODBC API and driver manager that
RDO Compared to Microsoft Jet/DAO establishes connections, creates result sets and cursors, and executes complex procedures using minimal workstation resources. Although RDO is also accessed by DAO when your code creates
an ODBCDirect Workspace object, documentation for this implementation can be found by searching for specific ODBCDirect topics.
Initializing the rdoEngine Object
Creating an rdoEnvironment Object Note RDO and the RemoteData control are designed to be used only in 32-bit operating systems such as Microsoft Windows 95 (or later) or Microsoft Windows NT.
Establishing an RDO Connection
Using RDO to Submit Queries Topics
Using RDO to Execute Stored Procedures
Creating RDO Cursors Features of Remote Data Objects

Working with RDO Result Sets


Introduces key capabilities of RDO.
Executing Optimistic Batch Updates
Using ODBC API Functions
Using the RemoteData Control
Programming with Remote Data Objects

Introduces the RDO object model.

RDO Compared to Microsoft Jet/DAO

Discusses what features are provided by RDO and how they map to more familiar DAO features.

Initializing the rdoEngine Object

An overview of the rdoEngine object and how to setup its properties.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRemoteDataObjectsRemoteDataControl.asp (1 of 3) [11/17/2002 11:23:04 PM]


Welcome to the MSDN Library

Creating an rdoEnvironment Object

An overview of the rdoEnvironment object and how to apply its properties to data access issues.

Establishing an RDO Connection

How to get connected to a remote data source.

Using RDO to Submit Queries

How to build and submit queries including parameter queries.

Using RDO to Execute Stored Procedures

How to work with the special requirements of stored procedures.

Creating RDO Cursors

Introduces techniques for creating cursors with RDO.

Working with RDO Result Sets

How to deal with the data and parameters returned from queries.

Executing Optimistic Batch Updates

How to use the optimistic batch update feature.

Using ODBC API Functions

Introduces the ODBC handles supported by RDO objects.

Using the RemoteData Control

How to retrieve data through bound controls using the RemoteData control.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRemoteDataObjectsRemoteDataControl.asp (2 of 3) [11/17/2002 11:23:04 PM]


Welcome to the MSDN Library
Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRemoteDataObjectsRemoteDataControl.asp (3 of 3) [11/17/2002 11:23:04 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control

MSDN Library GO
Advanced Search Visual Basic Concepts

Features of Remote Data Objects

See Also

Up One Level With RDO and the RemoteData control, your applications can access ODBC data sources without using a local query processor. This can mean significantly higher performance and more
flexibility when accessing remote database engines.
RDO Configuration Requirements
RDO and Client/Server Design Goals By using RDO, you can:

● Create simple cursorless result sets, or more complex cursors.

● Run queries and process any number of result sets.

● Execute stored procedures that return result sets with or without output parameters and return values.

● Execute action queries that perform data manipulation or data definition operations.

● Limit the number of rows returned or processed.

● Monitor all of the messages and errors generated by the remote data source without compromising the executing query.

● Enable synchronous, asynchronous, or event-driven asynchronous processing so your application isn't blocked while lengthy queries are executed or the current row pointer is repositioned.

About the User Connection Designer

The User Connection Designer uses Microsoft Visual Basic’s new class designer architecture to provide design-time support for programmatic data access. It allows you to create connection and
query objects (based on Remote Data Objects) at design time. These connections and queries are persisted as project-level objects. You can preset properties, define new properties and
methods, and write code behind the objects to trap events.

This provides a simplified method for responding to events raised from connections and queries as well as for calling stored procedures and client-defined queries at run time.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconIntroductionToRemoteDataObjects.asp [11/17/2002 11:23:10 PM]


RDO Configuration Requirements

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Features of Remote Data Objects

Visual Basic Concepts

RDO Configuration Requirements

See Also

Although you can access any ODBC data source with RDO and the RemoteData control, RDO is designed to take advantage of intelligent database servers, like Microsoft SQL Server and Oracle,
that use sophisticated query engines. If you connect to ODBC drivers that are not fully ODBC Level II compliant or to a less sophisticated data source, many RDO features cannot be enabled.

RDO 2.0 has relaxed many of the ODBC compliance requirements imposed by RDO 1.0. Specifically, RDO 2.0 now requires that your ODBC driver support only one Level II compliant operation that
enables the SQLNumParams ODBC API function. Without support for this ODBC Level II function, RDO cannot create the rdoParameters collection and parse parameter markers in SQL statements.
However, if the driver does not support the SQLProcedureColumns and SQLDescribeParam functions, then your code must supply the direction and data type for each parameter in the
rdoParameters collection.

While some drivers can be used to create and execute queries, if your driver does not support creation of the rdoParameters collection, RDO fails quietly and simply does not create the collection.
As a result, any reference to the collection results in a trappable error.

If you use RDO to access Microsoft Jet engine databases, the Jet engine must be loaded into memory and all ODBC requests are routed through Jet operations. Not only can this require more RAM
and CPU resources than using DAO, but many RDO functions are not supported by the fairly limited Jet ODBC drivers.

RDO is implemented as a 32-bit ActiveX interface, so your target system must be running Windows 95 (or later) or Windows NT.

In addition, RDO is only licensed to Visual Basic Enterprise Edition developers. While an RDO program can be compiled and distributed along with the RDO components to an unlimited number of
machines, the distributed version is only licensed for run-time operation. Other Microsoft Office platforms do not have a run-time mode or a license to act as an RDO development platform.
However, ODBCDirect is a licensed interface to RDO that can be used on Microsoft Office platforms.

Note RDO and the RemoteData control are 32-bit features of the Visual Basic, Enterprise Edition. You cannot develop code or use the RDO object library or RemoteData control in the Professional
or Learning Editions of Visual Basic or on 16-bit platforms.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconRDOConfigurationRequirements.asp?frame=true [11/17/2002 11:23:12 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Features of Remote Data Objects

MSDN Library GO
Advanced Search Visual Basic Concepts

RDO Configuration Requirements

See Also

Up One Level Although you can access any ODBC data source with RDO and the RemoteData control, RDO is designed to take advantage of intelligent database servers, like Microsoft SQL Server and Oracle,
that use sophisticated query engines. If you connect to ODBC drivers that are not fully ODBC Level II compliant or to a less sophisticated data source, many RDO features cannot be enabled.
RDO Configuration Requirements
RDO and Client/Server Design Goals RDO 2.0 has relaxed many of the ODBC compliance requirements imposed by RDO 1.0. Specifically, RDO 2.0 now requires that your ODBC driver support only one Level II compliant operation
that enables the SQLNumParams ODBC API function. Without support for this ODBC Level II function, RDO cannot create the rdoParameters collection and parse parameter markers in SQL
statements. However, if the driver does not support the SQLProcedureColumns and SQLDescribeParam functions, then your code must supply the direction and data type for each parameter in
the rdoParameters collection.

While some drivers can be used to create and execute queries, if your driver does not support creation of the rdoParameters collection, RDO fails quietly and simply does not create the
collection. As a result, any reference to the collection results in a trappable error.

If you use RDO to access Microsoft Jet engine databases, the Jet engine must be loaded into memory and all ODBC requests are routed through Jet operations. Not only can this require more
RAM and CPU resources than using DAO, but many RDO functions are not supported by the fairly limited Jet ODBC drivers.

RDO is implemented as a 32-bit ActiveX interface, so your target system must be running Windows 95 (or later) or Windows NT.

In addition, RDO is only licensed to Visual Basic Enterprise Edition developers. While an RDO program can be compiled and distributed along with the RDO components to an unlimited number
of machines, the distributed version is only licensed for run-time operation. Other Microsoft Office platforms do not have a run-time mode or a license to act as an RDO development platform.
However, ODBCDirect is a licensed interface to RDO that can be used on Microsoft Office platforms.

Note RDO and the RemoteData control are 32-bit features of the Visual Basic, Enterprise Edition. You cannot develop code or use the RDO object library or RemoteData control in the
Professional or Learning Editions of Visual Basic or on 16-bit platforms.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRDOConfigurationRequirements.asp [11/17/2002 11:23:15 PM]


RDO and Client/Server Design Goals

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Features of Remote Data Objects

Visual Basic Concepts

RDO and Client/Server Design Goals

See Also

RDO and the RemoteData control can help you meet a specific set of client/server requirements. By using these remote data access features, you can:

● Gain high-performance data access against remote ODBC data sources. The ability to quickly retrieve the results from complex queries is a goal of every data access application. RDO provides a level of performance rivaled only by the ODBC and VBSQL API
programming models. By leveraging the remote data engine, RDO greatly improves response time and user productivity.

● Manage return codes and both input and output parameters from stored procedures. Output parameters are the only way to extract information from an Oracle stored procedure, and are used heavily for singleton queries and many administrative
functions. In many cases, you cannot determine if a stored procedure completed successfully without accessing the procedure’s return value. RDO supports access to each of these parameters through the rdoParameter object.

● Manage multiple result sets. By using a single query that returns several sets of results, you can use the query processor and system resources more efficiently. You can improve performance by running a single query to gather data to fill multiple data-driven
list boxes and menus. In addition, by combining a row-count query with a SELECT query, you can accurately set up scroll bars and progress status bars.

● Submit multiple action queries in a single batch. In many cases, your application can submit a set of INSERT, DELETE or UPDATE operations as a single SQL statement. This increases performance, as it reduces network and remote processing overhead and
lets you manage transactions more easily.

● Limit the number of returned or processed rows. In situations where users might select more rows than it is practical to handle, RDO implements a query governor to limit the number of rows returned from any data source. This way, you can predict query
response time and more easily manage the workstation or server resources required to maintain cursor keysets. Using the same mechanism, you can limit the number of rows affected by a data-modification query.

● Utilize server-side cursors. Some servers, such as Microsoft SQL Server, support cursor keysets that are created on the server, instead of on the workstation. Under the right conditions, this type of cursor management can significantly improve performance and
reduce network load and workstation resource requirements.

● Execute queries asynchronously. If a query takes an extended period of time to run, you should have the option of either executing code while the query is being processed or canceling the query. RDO provides an asynchronous query option that you can use
when executing any query, as well as a way to cancel an asynchronous query. RDO also provides a unique event-driven asynchronous programming interface that eliminates the need for polling loops. Asynchronous processing extends to opening connections and
when using the MoveLast method.

● Continue queries after initial timeout period. When a query exhausts the period set in the QueryTimeout property, RDO permits you to override query cancellation and continue waiting for another timeout period.

● Support improved polymorphism and "free-standing" object creation. RDO now supports creation of rdoConnection and rdoQuery objects using the Dim statement. These free-standing objects can be associated with other objects to perform actions. For
example, you can create an rdoQuery object independent of any rdoConnection object and associate it with an open connection at a later time.

● Support dissociated result sets. RDO permits you to create a static read-write cursor and break the connection with the remote server. The data in the rdoResultset object remains available for access or changes. Once you re-associate the result set with
another rdoConnection object, you can use the BatchUpdate method to post these offline changes to the database.

● Create and manage optimistic batch updates. While the ODBC cursor library supports the concept of optimistic updates, it does so on a row by row basis rather than a batch basis. This type of update operation consumes considerable network and server
bandwidth. RDO leverages the new Client Batch cursor library that groups sets of rows to be inserted, updated, or deleted. This way, only one round trip to the server is needed, thus improving update performance and decreasing network traffic.

● Make the use of stored procedures easier. RDO permits you to express parameterized queries and stored procedures as methods of a parent rdoConnection object. You can pass parameters just as you would to any Visual Basic function without having to
manipulate any rdoParameter objects.

● Expose underlying ODBC handles. In cases where you need more flexibility or control than is available in the object model, you should have a way to directly access the data source. RDO provides access to the ODBC environment, connection, and statement
handles.

● Reduce memory footprint. In many cases, the system that hosts a client/server front-end application is limited in RAM capacity. Because of this, it is important that applications designed for these systems economize their use of RAM and other workstation
system resources. The RDO memory footprint is dramatically smaller than other programming models, and it does not require the use of local memory or disk space for its lowest-level cursors.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconClientServerDesignGoals.asp?frame=true [11/17/2002 11:23:18 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Features of Remote Data Objects

MSDN Library GO
Advanced Search Visual Basic Concepts

RDO and Client/Server Design Goals

See Also

Up One Level RDO and the RemoteData control can help you meet a specific set of client/server requirements. By using these remote data access features, you can:

RDO Configuration Requirements


RDO and Client/Server Design Goals ● Gain high-performance data access against remote ODBC data sources. The ability to quickly retrieve the results from complex queries is a goal of every data access application. RDO provides a level of performance rivaled only by the ODBC and
VBSQL API programming models. By leveraging the remote data engine, RDO greatly improves response time and user productivity.

● Manage return codes and both input and output parameters from stored procedures. Output parameters are the only way to extract information from an Oracle stored procedure, and are used heavily for singleton queries and many administrative
functions. In many cases, you cannot determine if a stored procedure completed successfully without accessing the procedure’s return value. RDO supports access to each of these parameters through the rdoParameter object.

● Manage multiple result sets. By using a single query that returns several sets of results, you can use the query processor and system resources more efficiently. You can improve performance by running a single query to gather data to fill multiple data-
driven list boxes and menus. In addition, by combining a row-count query with a SELECT query, you can accurately set up scroll bars and progress status bars.

● Submit multiple action queries in a single batch. In many cases, your application can submit a set of INSERT, DELETE or UPDATE operations as a single SQL statement. This increases performance, as it reduces network and remote processing overhead
and lets you manage transactions more easily.

● Limit the number of returned or processed rows. In situations where users might select more rows than it is practical to handle, RDO implements a query governor to limit the number of rows returned from any data source. This way, you can predict
query response time and more easily manage the workstation or server resources required to maintain cursor keysets. Using the same mechanism, you can limit the number of rows affected by a data-modification query.

● Utilize server-side cursors. Some servers, such as Microsoft SQL Server, support cursor keysets that are created on the server, instead of on the workstation. Under the right conditions, this type of cursor management can significantly improve
performance and reduce network load and workstation resource requirements.

● Execute queries asynchronously. If a query takes an extended period of time to run, you should have the option of either executing code while the query is being processed or canceling the query. RDO provides an asynchronous query option that you can
use when executing any query, as well as a way to cancel an asynchronous query. RDO also provides a unique event-driven asynchronous programming interface that eliminates the need for polling loops. Asynchronous processing extends to opening
connections and when using the MoveLast method.

● Continue queries after initial timeout period. When a query exhausts the period set in the QueryTimeout property, RDO permits you to override query cancellation and continue waiting for another timeout period.

● Support improved polymorphism and "free-standing" object creation. RDO now supports creation of rdoConnection and rdoQuery objects using the Dim statement. These free-standing objects can be associated with other objects to perform actions.
For example, you can create an rdoQuery object independent of any rdoConnection object and associate it with an open connection at a later time.

● Support dissociated result sets. RDO permits you to create a static read-write cursor and break the connection with the remote server. The data in the rdoResultset object remains available for access or changes. Once you re-associate the result set with
another rdoConnection object, you can use the BatchUpdate method to post these offline changes to the database.

● Create and manage optimistic batch updates. While the ODBC cursor library supports the concept of optimistic updates, it does so on a row by row basis rather than a batch basis. This type of update operation consumes considerable network and server
bandwidth. RDO leverages the new Client Batch cursor library that groups sets of rows to be inserted, updated, or deleted. This way, only one round trip to the server is needed, thus improving update performance and decreasing network traffic.

● Make the use of stored procedures easier. RDO permits you to express parameterized queries and stored procedures as methods of a parent rdoConnection object. You can pass parameters just as you would to any Visual Basic function without having to
manipulate any rdoParameter objects.

● Expose underlying ODBC handles. In cases where you need more flexibility or control than is available in the object model, you should have a way to directly access the data source. RDO provides access to the ODBC environment, connection, and
statement handles.

● Reduce memory footprint. In many cases, the system that hosts a client/server front-end application is limited in RAM capacity. Because of this, it is important that applications designed for these systems economize their use of RAM and other workstation
system resources. The RDO memory footprint is dramatically smaller than other programming models, and it does not require the use of local memory or disk space for its lowest-level cursors.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconClientServerDesignGoals.asp [11/17/2002 11:23:21 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control

MSDN Library GO
Advanced Search Visual Basic Concepts

Programming with Remote Data Objects

See Also

Up One Level RDO objects and collections provide a framework for using code to create and manipulate components of a remote ODBC database system. Objects and collections have properties that describe
the characteristics of database components and methods that you use to manipulate them. Using the containment framework, you create relationships among objects and collections, and these
Creating Remote Data Objects relationships represent the logical structure of your database system.

Figure 11.1 The RDO 2.0 object model

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRemoteDataObjects.asp (1 of 3) [11/17/2002 11:23:29 PM]


Welcome to the MSDN Library

With the exception of the rdoEngine object, each of these objects is maintained in an associated collection. When RDO is initialized on first access, RDO automatically creates an instance of the
rdoEngine and the default rdoEnvironments(0).

The Remote Data Object programming model is similar to the Data Access Objects (DAO) programming model in many respects. However, far more emphasis is focused on handling stored
procedures and their result sets, and less emphasis is placed on data access retrieval methods used solely by ISAM programming models. The following table describes each of the objects.

RDO object Description

rdoEngine The base object. Created automatically when you first access RDO in your application.

rdoError Used to handle all ODBC errors and messages generated by RDO. Created automatically.

rdoEnvironment Defines a logical set of connections and transaction scope for a particular user name. Contains both open and allocated (but unopened) connections, provides
mechanisms for simultaneous transactions, and provides a security context for data manipulation language (DML) operations on the database. rdoEnvironments(0)
created automatically.

rdoConnection Represents an open connection to a remote data source and a specific database on that data source, or an allocated but as yet unconnected object, which can be
used to subsequently establish a connection.

rdoTable Represents the stored definition of a base table or an SQL view.

rdoResultset Represents the rows that result from running a query.

rdoColumn Represents a column of data with a common data type and a common set of properties.

rdoQuery An SQL query definition that can include zero or more parameters.

rdoParameter Represents a parameter associated with an rdoQuery object. Query parameters can be input, output, or both.

Note True distributed transactions can only be done between database management systems that support the Distributed Transaction Coordinator (DTC). At this time, only Microsoft SQL
Server 6.5 supports this functionality. For more information about DTC, see "Using the rdoEnvironment Object to Manage Transactions" in this chapter.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRemoteDataObjects.asp (2 of 3) [11/17/2002 11:23:29 PM]


Welcome to the MSDN Library

Note The RDO 1.0 rdoPreparedStatement object and rdoPreparedStatements collection are supported by RDO 2.0, but only for backward compatibility. You should convert your code to use
the rdoQuery object and rdoQueries collection instead.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRemoteDataObjects.asp (3 of 3) [11/17/2002 11:23:29 PM]


Creating Remote Data Objects

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Programming with Remote Data Objects

Visual Basic Concepts

Creating Remote Data Objects

See Also

You can use the RemoteData control to create RDO objects, just as you can use the Data control to create DAO objects. You can also create result sets using RDO methods and pass them to the
RemoteData control for management and editing by associated bound controls.

Remote Data Objects are also created by using methods on the parent object, or by declaring the objects with the Dim statement. If you use the Dim as New statement to instantiate a new object,
the object is not appended to the associated collection. The following table shows how to create each of the primary Remote Data Objects:

Remote Data Object How created

rdoEngine Created automatically.

rdoEnvironment First instance created automatically. rdoEngine.rdoCreateEnvironment

rdoConnection rdoEnvironment(x).OpenConnection
(can also be created by the RemoteData control)
Dim MyCn as New rdoConnection

rdoQuery rdoConnections(x).CreateQuery
Dim MyQry as New rdoQuery

rdoResultset rdoQuery(x).OpenResultset
rdoConnection(x).OpenResultset
(can also be created by the RemoteData control)

rdoParameter Created automatically for parameter queries.

rdoTable Created automatically when referenced.

rdoError Created automatically when ODBC errors or messages are returned.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreatingRemoteDataObjects.asp?frame=true [11/17/2002 11:23:33 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Programming with Remote Data Objects

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating Remote Data Objects

See Also

Up One Level You can use the RemoteData control to create RDO objects, just as you can use the Data control to create DAO objects. You can also create result sets using RDO methods and pass them to the
RemoteData control for management and editing by associated bound controls.
Creating Remote Data Objects
Remote Data Objects are also created by using methods on the parent object, or by declaring the objects with the Dim statement. If you use the Dim as New statement to instantiate a new
object, the object is not appended to the associated collection. The following table shows how to create each of the primary Remote Data Objects:

Remote Data Object How created

rdoEngine Created automatically.

rdoEnvironment First instance created automatically. rdoEngine.rdoCreateEnvironment

rdoConnection rdoEnvironment(x).OpenConnection
(can also be created by the RemoteData control)
Dim MyCn as New rdoConnection

rdoQuery rdoConnections(x).CreateQuery
Dim MyQry as New rdoQuery

rdoResultset rdoQuery(x).OpenResultset
rdoConnection(x).OpenResultset
(can also be created by the RemoteData control)

rdoParameter Created automatically for parameter queries.

rdoTable Created automatically when referenced.

rdoError Created automatically when ODBC errors or messages are returned.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingRemoteDataObjects.asp [11/17/2002 11:23:35 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control

MSDN Library GO
Advanced Search Visual Basic Concepts

RDO Compared to Microsoft Jet/DAO

See Also

Up One Level Basically, you can use Remote Data Objects similarly to the way you use the Microsoft Jet database engine Data Access Objects (DAO), and the RemoteData control is similar to the Data
control. With RDO, you can submit queries, create a result set or cursor, and process the results from the query using database-independent object-oriented code.
RDO Collection Management
RDO Compared to Microsoft Jet ODBCDirect Using the RemoteData control, you can create a form containing the same bound controls recognized by the Data control and process a result set with little or no code.

You can take your existing applications that use DAO and the Data control and convert them to use RDO and the RemoteData control with a few changes. There are some differences, however,
because RDO is implemented and designed for use with strictly relational databases. RDO has no query processor of its own; it depends on the data source to process all queries and create the
result sets. The data objects themselves are built from the result sets and cursors returned by the ODBC driver.

It might be unnecessary to convert an existing DAO/Jet application over to RDO because of ODBCDirect, which routes DAO through RDO instead of Jet. If your application does not use the DAO
ISAM objects and methods (like the table-type Recordset object and the Seek method) or other ISAM programming methodologies, you should be able to convert over to ODBCDirect with very
few changes — even fewer than are required when converting to RDO.

For More Information For more information about ODBCDirect, see "RDO Compared to Microsoft Jet ODBCDirect" and "Remote Data Access Using DAO and ODBCDirect" in "Using Data
Access Objects"

The following table lists RDO 2.0 objects and their equivalent DAO/Jet objects.

Remote Data Objects and their DAO/Jet Equivalents

RDO object Equivalent DAO/Jet object

rdoEngine DBEngine

rdoError Error

rdoEnvironment Workspace

rdoConnection Database

rdoTable TableDef

Not Implemented Index

rdoResultset Recordset

Not implemented Table-type

Keyset-type Dynaset-type

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRDOComparedToMicrosoftJet.asp (1 of 2) [11/17/2002 11:23:43 PM]


Welcome to the MSDN Library
Static-type (r/w) Snapshot-type (r/o)

Dynamic-type (none)

Forward-only – type Forward-only-type

(cursorless) (none)

rdoColumn Field

rdoQuery QueryDef

rdoParameter Parameter

Not Implemented Relation

Not Implemented Group

Not implemented User

Remote Data Objects refer to table rows instead of records and columns instead of fields — the generally accepted terminology for relational databases. The data returned from a query is in
the form of result sets, which can contain zero or more data rows composed of one or more columns. Whereas DAO requires cursors to access data, RDO permits you to create a cursorless
result set that has far fewer resource demands than a cursor.

Some DAO objects, methods, and properties are designed to implement and support the ISAM structure of Jet and installable ISAM databases. For example, you can use the Index object and
the Seek method to manage ISAM indexes and locate rows based on those indexes. Because the RDO and relational databases manage indexes in an entirely different manner, those objects
and methods are not needed.

DAO also supports the creation and modification of the database schema, referential integrity (RI), and security through DAO methods and properties. RDO does not support any type of RI,
security, or schema modification because they are fully supported in the tools and utilities provided with the server systems.

You can still run RDO make-table queries or execute action queries that create, modify, or delete databases and tables using native SQL statements. You can also execute complex stored
procedures that manage the database schema or perform maintenance operations that are not possible with DAO.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRDOComparedToMicrosoftJet.asp (2 of 2) [11/17/2002 11:23:43 PM]


RDO Collection Management

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > RDO Compared to Microsoft Jet/DAO

Visual Basic Concepts

RDO Collection Management

See Also

RDO uses a collection to manage each of the RDO objects except the RDO engine itself. Because Visual Basic version 6.0 now supports the creation of some stand-alone objects like rdoConnection
and rdoQuery objects, not all objects are automatically appended to their parent collection — but in most cases, this is done automatically. Stand-alone rdoConnection and rdoQuery objects can be
appended to their parent collection using the Add method and can be removed from the collection using the Remove method.

The rdoParameters collection is automatically created when using the CreateQuery method. However, if the ODBC interface cannot parse the SQL syntax for any reason, this collection used to
manage a query's parameters is not created. Therefore, any reference to the rdoParameters collection will result in a trappable error unless RDO successfully parses the SQL parameter query as
specified in the SQL property of the rdoQuery object. This collection is also not populated if the ODBC data source driver does not support the SQLNumParams function or if this function returns an
error.

The following table lists the collections managed by RDO:

RDO collection Description

rdoErrors Contains all stored rdoError objects which pertain to a single operation involving Remote Data Objects (RDO).

rdoEnvironments Contains all active rdoEnvironment objects of the rdoEngine object. rdoEnvironments(0) is created automatically.

rdoConnections Contains all rdoConnection objects opened or created in an rdoEnvironment object, or allocated and appended to the rdoConnections collection using the Add method.

rdoTables Contains all stored rdoTable objects in a database.

rdoResultsets Contains all open rdoResultset objects in an rdoConnection.

rdoColumns Contains all rdoColumn objects of an rdoResultset or rdoTable object.

rdoQueries Contains rdoQuery objects that have been added to the rdoQueries collection either automatically via the CreateQuery method, or with the Add method.

rdoParameters Contains all the rdoParameter objects of an rdoQuery object once the SQL statement is successfully parsed. Contains an rdoParameter object for each marked parameter
in the query.

RDO 1.0 Collections

RDO 1.0 objects and their collections are managed differently than RDO 2.0 objects and collections. When you open or create a new RDO 1.0 object, it is automatically appended to the collection
associated with those objects, even when you set an existing variable to the newly created object.

For example, the following RDO 1.0 code creates two independent rdoConnection objects:

Dim Cn as rdoConnection
Set Cn = rdoEnvironments(0).OpenConnection( _
dsname:="MyDSN", _
prompt:=rdDriverNoPrompt, _
connect:="UID=;PWD=;")
Set Cn = rdoEnvironments(0).OpenConnection( _
dsname:="MyOtherDSN", _
prompt:=rdDriverNoPrompt, _
connect:="UID=;PWD=;")

After this code is executed, both RDO 1.0 rdoConnection objects are appended as members of the rdoConnections collection. With this behavior in mind, your code must use the Close method on
objects that are no longer needed as they are not automatically closed — even when assigned to the same variable. This same behavior applies to rdoResultset objects as well.

RDO 2.0 Collections

In RDO 2.0, setting an existing variable to a newly created object releases or closes the existing RDO object before replacing it with the newly created RDO object. This change makes RDO work
more like DAO objects.

When the code shown above is executed in Visual Basic using RDO 2.0, only one rdoConnection object is created: The first rdoConnection object is closed and removed from the rdoConnections
collection. If your Visual Basic version 4.0 code explicitly closes RDO connections and rdoResultset objects, you need not be concerned with backward compatibility. However, if you depend on
these objects to be maintained, then you must assign new RDO objects to new variables or the original object will be lost.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconRDOCollectionManagement.asp?frame=true (1 of 2) [11/17/2002 11:23:46 PM]


RDO Collection Management

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconRDOCollectionManagement.asp?frame=true (2 of 2) [11/17/2002 11:23:46 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > RDO Compared to Microsoft Jet/DAO

MSDN Library GO
Advanced Search Visual Basic Concepts

RDO Collection Management

See Also

Up One Level RDO uses a collection to manage each of the RDO objects except the RDO engine itself. Because Visual Basic version 6.0 now supports the creation of some stand-alone objects like
rdoConnection and rdoQuery objects, not all objects are automatically appended to their parent collection — but in most cases, this is done automatically. Stand-alone rdoConnection and
RDO Collection Management rdoQuery objects can be appended to their parent collection using the Add method and can be removed from the collection using the Remove method.

RDO Compared to Microsoft Jet ODBCDirect


The rdoParameters collection is automatically created when using the CreateQuery method. However, if the ODBC interface cannot parse the SQL syntax for any reason, this collection used to
manage a query's parameters is not created. Therefore, any reference to the rdoParameters collection will result in a trappable error unless RDO successfully parses the SQL parameter query
as specified in the SQL property of the rdoQuery object. This collection is also not populated if the ODBC data source driver does not support the SQLNumParams function or if this function
returns an error.

The following table lists the collections managed by RDO:

RDO collection Description

rdoErrors Contains all stored rdoError objects which pertain to a single operation involving Remote Data Objects (RDO).

rdoEnvironments Contains all active rdoEnvironment objects of the rdoEngine object. rdoEnvironments(0) is created automatically.

rdoConnections Contains all rdoConnection objects opened or created in an rdoEnvironment object, or allocated and appended to the rdoConnections collection using the Add method.

rdoTables Contains all stored rdoTable objects in a database.

rdoResultsets Contains all open rdoResultset objects in an rdoConnection.

rdoColumns Contains all rdoColumn objects of an rdoResultset or rdoTable object.

rdoQueries Contains rdoQuery objects that have been added to the rdoQueries collection either automatically via the CreateQuery method, or with the Add method.

rdoParameters Contains all the rdoParameter objects of an rdoQuery object once the SQL statement is successfully parsed. Contains an rdoParameter object for each marked
parameter in the query.

RDO 1.0 Collections

RDO 1.0 objects and their collections are managed differently than RDO 2.0 objects and collections. When you open or create a new RDO 1.0 object, it is automatically appended to the
collection associated with those objects, even when you set an existing variable to the newly created object.

For example, the following RDO 1.0 code creates two independent rdoConnection objects:

Dim Cn as rdoConnection
Set Cn = rdoEnvironments(0).OpenConnection( _
dsname:="MyDSN", _
prompt:=rdDriverNoPrompt, _
connect:="UID=;PWD=;")
Set Cn = rdoEnvironments(0).OpenConnection( _
dsname:="MyOtherDSN", _

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRDOCollectionManagement.asp (1 of 2) [11/17/2002 11:23:48 PM]


Welcome to the MSDN Library
prompt:=rdDriverNoPrompt, _
connect:="UID=;PWD=;")

After this code is executed, both RDO 1.0 rdoConnection objects are appended as members of the rdoConnections collection. With this behavior in mind, your code must use the Close method
on objects that are no longer needed as they are not automatically closed — even when assigned to the same variable. This same behavior applies to rdoResultset objects as well.

RDO 2.0 Collections

In RDO 2.0, setting an existing variable to a newly created object releases or closes the existing RDO object before replacing it with the newly created RDO object. This change makes RDO
work more like DAO objects.

When the code shown above is executed in Visual Basic using RDO 2.0, only one rdoConnection object is created: The first rdoConnection object is closed and removed from the rdoConnections
collection. If your Visual Basic version 4.0 code explicitly closes RDO connections and rdoResultset objects, you need not be concerned with backward compatibility. However, if you depend on
these objects to be maintained, then you must assign new RDO objects to new variables or the original object will be lost.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRDOCollectionManagement.asp (2 of 2) [11/17/2002 11:23:48 PM]


RDO Compared to Microsoft Jet ODBCDirect

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > RDO Compared to Microsoft Jet/DAO

Visual Basic Concepts

RDO Compared to Microsoft Jet ODBCDirect

See Also

DAO supports an object interface option that links the DAO object model to Remote Data Objects. This new interface, referred to as ODBCDirect, vectors DAO references to equivalent RDO objects
once the DBEngine object's DefaultType property is set. If ODBCDirect is enabled, DAO does not load the Microsoft Jet database engine — it loads RDO 2.0 instead.

Generally, this interface is designed for developers who need to maintain a degree of source-code compatibility between DAO/Jet and DAO/ODBCDirect applications. For example, in cases where a
single application must be written to access both native Jet and ODBC-accessed databases, ODBCDirect can provide a similar programming paradigm.

Note While the object names used in ODBCDirect are roughly the same as those used in DAO/Jet, some properties and methods that can be applied to DAO/Jet objects cannot be used with
ODBCDirect Recordset objects. Similarly, some properties and methods exposed by ODBCDirect Recordset objects cannot be used with DAO/Jet Recordset objects. In addition, not all RDO 2.0
functionality is exposed in ODBCDirect.

For More Information For more information about ODBCDirect, see "Remote Data Access Using DAO and ODBCDirect" in "Using Data Access Objects."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/ht...RDOComparedToMicrosoftJetODBCDirect.asp?frame=true [11/17/2002 11:23:52 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > RDO Compared to Microsoft Jet/DAO

MSDN Library GO
Advanced Search Visual Basic Concepts

RDO Compared to Microsoft Jet ODBCDirect

See Also

Up One Level DAO supports an object interface option that links the DAO object model to Remote Data Objects. This new interface, referred to as ODBCDirect, vectors DAO references to equivalent RDO
objects once the DBEngine object's DefaultType property is set. If ODBCDirect is enabled, DAO does not load the Microsoft Jet database engine — it loads RDO 2.0 instead.
RDO Collection Management
RDO Compared to Microsoft Jet ODBCDirect Generally, this interface is designed for developers who need to maintain a degree of source-code compatibility between DAO/Jet and DAO/ODBCDirect applications. For example, in cases
where a single application must be written to access both native Jet and ODBC-accessed databases, ODBCDirect can provide a similar programming paradigm.

Note While the object names used in ODBCDirect are roughly the same as those used in DAO/Jet, some properties and methods that can be applied to DAO/Jet objects cannot be used with
ODBCDirect Recordset objects. Similarly, some properties and methods exposed by ODBCDirect Recordset objects cannot be used with DAO/Jet Recordset objects. In addition, not all RDO 2.0
functionality is exposed in ODBCDirect.

For More Information For more information about ODBCDirect, see "Remote Data Access Using DAO and ODBCDirect" in "Using Data Access Objects."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconRDOComparedToMicrosoftJetODBCDirect.asp [11/17/2002 11:23:54 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control

MSDN Library GO
Advanced Search Visual Basic Concepts

Initializing the rdoEngine Object

See Also

Up One Level The rdoEngine object represents the remote data source and is created automatically when you first make reference to an RDO object or the RemoteData control. As the top-level object, it
contains all the other objects in the hierarchy of Remote Data Objects. The rdoEngine object is predefined, therefore you can’t create additional rdoEngine objects, and it isn’t a member of any
Initializing rdoEngine Default Properties collection. You can use the rdoEngine to set data source parameters and create additional rdoEnvironment objects.

Managing RDO Errors and Messages


Even though the rdoEngine is shared among the various applications that use it, the rdoEngine default properties are not shared between applications. Each instance of your application is
provided with its own set of default values that have no effect on other applications that also use RDO or the RemoteData control.

Note Adding the RemoteData control to your Toolbox does not automatically set a reference to the Microsoft Remote Data Object library. To use the rdoEngine and Remote Data Objects from
code, you must set a reference to the Microsoft Remote Data Object 2.0 object library in the References dialog box (available from the Projects menu); otherwise, you will get a compilation
error when the first RDO object is referenced. Also, If you have Visual Basic version 4.0 or Microsoft Office installed on your computer, the RDO 1.0 library might appear in the list of object
libraries exposed by the Project References dialog. While using this library is possible with Visual Basic version 5.0 or later, it is not recommended.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconTheRdoEngineObject.asp [11/17/2002 11:24:04 PM]


Initializing rdoEngine Default Properties

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Initializing the rdoEngine Object

Visual Basic Concepts

Initializing rdoEngine Default Properties

See Also

When you create new rdoEnvironment, rdoConnection, or rdoResultset objects, the characteristics of the new objects are determined by the arguments in the rdoCreateEnvironment or
OpenResultset method, or by the default values in the default properties of the rdoEngine. These properties are listed in the following table.

Property Specifies Default

rdoDefaultCursorDriver Cursor library (ODBC, client batch, server-side, or none) rdUseIfNeeded (server-side cursors)

rdoDefaultPassword User password "" (empty string)

rdoDefaultUser User ID "" (empty string)

rdoDefaultErrorThreshold Error severity above which errors are fatal -1 (disabled)

rdoDefaultLoginTimeout Time to wait before abandoning connection attempt 15 seconds

You can change any of these default value properties before creating new rdoEnvironment, rdoConnection, or rdoResultset objects. However, rdoEnvironments(0) is created using the defaults
shown in the preceding table because it is created automatically on the first reference to RDO or the RemoteData control. If the default values are not appropriate for your application, you must
change the properties of rdoEnvironments(0) or the rdoEngine before creating a new rdoEnvironment object or opening a connection.

Trapping the InfoMessage Event

The rdoEngine fires the InfoMessage event when the ODBC interface receives an informational message from the remote server. This event is raised after RDO receives a
SQL_SUCCESS_WITH_INFO return code and populates the rdoErrors collection with the informational messages. If an RDO method call generates many informational messages, this event will be
raised only once, after the last informational message has been added to the collection. You can trap this event and examine the contents of the rdoErrors collection and then decide what action is
appropriate.

For example, if you submit a query that enables statistics or query plan information from SQL Server, this information is returned through the rdoErrors collection, and your application is notified
that these messages are available when the InfoMessage event is fired.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/v...nInitializingRdoEngineDefaultProperties.asp?frame=true [11/17/2002 11:24:08 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Initializing the rdoEngine Object

MSDN Library GO
Advanced Search Visual Basic Concepts

Initializing rdoEngine Default Properties

See Also

Up One Level When you create new rdoEnvironment, rdoConnection, or rdoResultset objects, the characteristics of the new objects are determined by the arguments in the rdoCreateEnvironment or
OpenResultset method, or by the default values in the default properties of the rdoEngine. These properties are listed in the following table.
Initializing rdoEngine Default Properties
Managing RDO Errors and Messages
Property Specifies Default

rdoDefaultCursorDriver Cursor library (ODBC, client batch, server-side, or none) rdUseIfNeeded (server-side cursors)

rdoDefaultPassword User password "" (empty string)

rdoDefaultUser User ID "" (empty string)

rdoDefaultErrorThreshold Error severity above which errors are fatal -1 (disabled)

rdoDefaultLoginTimeout Time to wait before abandoning connection attempt 15 seconds

You can change any of these default value properties before creating new rdoEnvironment, rdoConnection, or rdoResultset objects. However, rdoEnvironments(0) is created using the defaults
shown in the preceding table because it is created automatically on the first reference to RDO or the RemoteData control. If the default values are not appropriate for your application, you must
change the properties of rdoEnvironments(0) or the rdoEngine before creating a new rdoEnvironment object or opening a connection.

Trapping the InfoMessage Event

The rdoEngine fires the InfoMessage event when the ODBC interface receives an informational message from the remote server. This event is raised after RDO receives a
SQL_SUCCESS_WITH_INFO return code and populates the rdoErrors collection with the informational messages. If an RDO method call generates many informational messages, this event will
be raised only once, after the last informational message has been added to the collection. You can trap this event and examine the contents of the rdoErrors collection and then decide what
action is appropriate.

For example, if you submit a query that enables statistics or query plan information from SQL Server, this information is returned through the rdoErrors collection, and your application is
notified that these messages are available when the InfoMessage event is fired.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconInitializingRdoEngineDefaultProperties.asp [11/17/2002 11:26:56 PM]


Managing RDO Errors and Messages

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Initializing the rdoEngine Object

Visual Basic Concepts

Managing RDO Errors and Messages

See Also

Each time the ODBC driver manager is used to carry out an RDO request, an error can be generated by Visual Basic, the ODBC interface, or the remote server. These errors can be of varying
severity and in some cases may force the query to be canceled or abandoned.

Any errors generated by Visual Basic trigger a trappable error that you can trap using the On Error statement. Errors generated by the ODBC middleware or by the remote server are placed in the
rdoErrors collection. Whenever the ODBC function being called by RDO returns a SQL_ERROR result code, Visual Basic fires a trappable error indicating that an ODBC error has occurred. At this
point your code can examine the individual members of the rdoErrors collection for details on what caused the error.

Whenever the return code from the ODBC API function is set to SQL_SUCCESS_WITH_INFO, an Informational message is returned from the data source that does not trigger a trappable error.
These messages are placed in the rdoErrors collection.

Visual Basic also produces a trappable error when an error occurs that is not directly related to an ODBC operation. For example, if you execute the CreateQuery method and then try to set the
rdoParameters collection, you might trip a trappable error indicating that the object does not exist. This can be caused by RDO's inability to build an rdoParameters collection based on the query's
syntax. You can examine the Err and Error properties in your On Error handler to determine what action should be taken.

Once you examine the rdoErrors collection, you can clear its contents by using the Clear method. This prevents the confusion that can occur if you subsequently check the rdoErrors collection for
errors, only to discover residual messages from an earlier operation that could have no bearing on the current problem.

When you execute a query, the QueryComplete event fires — whether or not the query executed successfully. You can examine the ErrorOccurred Boolean flag to check for successful completion
of the query. In a similar fashion, you can check the ErrorOccurred flag in the Connected event to check for the success or failure of a connection operation.

For More Information See "rdoError Object" or "rdoDefaultErrorThreshold Property" in the Language Reference".

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconManagingRDOErrorsMessages.asp?frame=true [11/17/2002 11:32:13 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Initializing the rdoEngine Object

MSDN Library GO
Advanced Search Visual Basic Concepts

Managing RDO Errors and Messages

See Also

Up One Level Each time the ODBC driver manager is used to carry out an RDO request, an error can be generated by Visual Basic, the ODBC interface, or the remote server. These errors can be of varying
severity and in some cases may force the query to be canceled or abandoned.
Initializing rdoEngine Default Properties
Managing RDO Errors and Messages Any errors generated by Visual Basic trigger a trappable error that you can trap using the On Error statement. Errors generated by the ODBC middleware or by the remote server are placed in
the rdoErrors collection. Whenever the ODBC function being called by RDO returns a SQL_ERROR result code, Visual Basic fires a trappable error indicating that an ODBC error has occurred. At
this point your code can examine the individual members of the rdoErrors collection for details on what caused the error.

Whenever the return code from the ODBC API function is set to SQL_SUCCESS_WITH_INFO, an Informational message is returned from the data source that does not trigger a trappable error.
These messages are placed in the rdoErrors collection.

Visual Basic also produces a trappable error when an error occurs that is not directly related to an ODBC operation. For example, if you execute the CreateQuery method and then try to set the
rdoParameters collection, you might trip a trappable error indicating that the object does not exist. This can be caused by RDO's inability to build an rdoParameters collection based on the
query's syntax. You can examine the Err and Error properties in your On Error handler to determine what action should be taken.

Once you examine the rdoErrors collection, you can clear its contents by using the Clear method. This prevents the confusion that can occur if you subsequently check the rdoErrors collection
for errors, only to discover residual messages from an earlier operation that could have no bearing on the current problem.

When you execute a query, the QueryComplete event fires — whether or not the query executed successfully. You can examine the ErrorOccurred Boolean flag to check for successful
completion of the query. In a similar fashion, you can check the ErrorOccurred flag in the Connected event to check for the success or failure of a connection operation.

For More Information See "rdoError Object" or "rdoDefaultErrorThreshold Property" in the Language Reference".

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconManagingRDOErrorsMessages.asp [11/17/2002 11:32:17 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating an rdoEnvironment Object

See Also

Up One Level In most cases, your application need not create an additional rdoEnvironment object — the default rdoEnvironments(0) should suffice for most operations. However, if your application expects
to support more than one transaction scope, or separate user name and password contexts, you should use the rdoCreateEnvironment method to create a new rdoEnvironment object with
Using the rdoEnvironment Object to Manage Transactions specific user name and password values. This method accepts a unique name, a user name, and password. If the name you choose matches the name of an existing member of the
rdoEnvironments collection, a trappable error results.
Managing Connections with the rdoEnvironment Object
The default rdoEnvironments(0) is created automatically when the RemoteData control is initialized, or when the first RDO object is referenced in code. The Name property of
rdoEnvironments(0) is "Default_Environment." The user name and password for rdoEnvironments(0) are both zero-length strings ("").

Newly created rdoEnvironment objects are automatically appended to the rdoEnvironments collection if you provide a unique name. You can also use a zero-length string for the name
argument of the rdoCreateEnvironment method. In this case, the new rdoEnvironment is not appended to the rdoEnvironments collection.

Cached Logon Information

The user name and password information from the rdoEnvironment is used to establish the connection if these values are not supplied in the connect argument of the OpenConnection
method, or in the Connect property of the RemoteData control.

For example, the default user name (Fred) and password (Blond) can be used to establish a connection in the En environment:

Dim En As rdoEnvironment
Set En = rdoCreateEnvironment("", "Fred", "Blond")

An rdoEnvironment object logically corresponds to an ODBC environment. You can refer to an rdoEnvironment object using the ODBC API functions, by referencing an rdoEnvironment object's
hEnv property. However, because ODBC implementations only allow one environment handle per application, the actual lifetime of the ODBC environment handle is tied to the lifetime of the
rdoEngine.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingRdoEnvironment.asp [11/17/2002 11:33:50 PM]


Using the rdoEnvironment Object to Manage Transactions

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Creating an rdoEnvironment Object

Visual Basic Concepts

Using the rdoEnvironment Object to Manage Transactions

See Also

The BeginTrans, CommitTrans, and RollbackTrans methods are all supported on the rdoEnvironment object to begin, commit, or roll back ODBC distributed transactions. These methods are
implemented using the Distributed Transaction Coordinator (DTC) on systems that support this technology. At this time, only Microsoft SQL Server 6.5 supports DTC. All connections in the
rdoConnections collection for the rdoEnvironment object participate in the distributed transaction.

The Microsoft Distributed Transaction Coordinator (MS DTC)

This new feature of Microsoft SQL Server coordinates transactions across a network of Microsoft Windows NT– and Microsoft Windows 95/98–based systems. With MS DTC, SQL Server can:

● Update data that resides on two or more SQL Server 6.5 systems.

● Participate in transactions that are controlled by X/Open DTP XA-compliant transaction-processing monitors, such as Transarc's Encina, AT&T Global Information Solutions Company's Top End, and Tuxedo.

● Provide an easy-to-use graphical user interface for distributed transactions.

You can also use MS DTC by using the Distributed Transaction Coordinator command from the Server menu.

Microsoft Distributed Transaction Coordinator addresses the challenges of processing transactions over a distributed set of software components that exist on a system of networked computers. MS
DTC is fully integrated with Microsoft SQL Server 6.5 and provides a transaction manager in SQL Enterprise Manager at each computer that manages distributed transactions.

RDO DTC-Independent Transaction Management

If the DTC is not available, or if the current ODBC driver cannot handle a distributed transaction, these methods force RDO to perform a serialized transaction across all connections in the
rdoConnections collection. But these transactions are not atomic — that is, operations executed against one rdoConnection could complete, but those against another might not. In this case, the
committed operations are not rolled back. Because of this, their success or failure is not interdependent.

Because the rdoEnvironment object determines transaction scope in your application, committing an rdoEnvironment transaction commits all pending transactions on all open rdoConnection
databases (which are opened on that rdoEnvironment object and their corresponding open rdoResultset objects). This does not imply a two-phase commit operation. It simply means that
individual rdoConnection objects are instructed to commit any pending transactions — one at a time.

Note The ODBC transaction model does not support nested transactions. That is, you cannot execute a second BeginTrans method before the previous transaction is either committed or rolled
back. However, if your ODBC data source supports it, you can use SQL statements to execute nested transactions. This is supported by all Microsoft SQL Server systems.

When you use ODBC transactions, transactions do not span connections: Transactions begun and committed on one connection do not affect transactions pending on other connections, even if
both connections are made to the same server and database.

Trapping rdoEnvironment Transaction Events

The rdoEnvironment object fires an event whenever a transaction operation has completed. These events can be used to synchronize other processes with the transaction state. Basically, the
BeginTrans, CommitTrans, and RollbackTrans event fire after the corresponding method has fired.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html...EnvironmentObjectToManageTransactions.asp?frame=true [11/17/2002 11:35:47 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Creating an rdoEnvironment Object

MSDN Library GO
Advanced Search Visual Basic Concepts

Using the rdoEnvironment Object to Manage Transactions

See Also

Up One Level The BeginTrans, CommitTrans, and RollbackTrans methods are all supported on the rdoEnvironment object to begin, commit, or roll back ODBC distributed transactions. These methods are
implemented using the Distributed Transaction Coordinator (DTC) on systems that support this technology. At this time, only Microsoft SQL Server 6.5 supports DTC. All connections in the
Using the rdoEnvironment Object to Manage Transactions rdoConnections collection for the rdoEnvironment object participate in the distributed transaction.

Managing Connections with the rdoEnvironment Object


The Microsoft Distributed Transaction Coordinator (MS DTC)

This new feature of Microsoft SQL Server coordinates transactions across a network of Microsoft Windows NT– and Microsoft Windows 95/98–based systems. With MS DTC, SQL Server can:

● Update data that resides on two or more SQL Server 6.5 systems.

● Participate in transactions that are controlled by X/Open DTP XA-compliant transaction-processing monitors, such as Transarc's Encina, AT&T Global Information Solutions Company's Top End, and Tuxedo.

● Provide an easy-to-use graphical user interface for distributed transactions.

You can also use MS DTC by using the Distributed Transaction Coordinator command from the Server menu.

Microsoft Distributed Transaction Coordinator addresses the challenges of processing transactions over a distributed set of software components that exist on a system of networked
computers. MS DTC is fully integrated with Microsoft SQL Server 6.5 and provides a transaction manager in SQL Enterprise Manager at each computer that manages distributed transactions.

RDO DTC-Independent Transaction Management

If the DTC is not available, or if the current ODBC driver cannot handle a distributed transaction, these methods force RDO to perform a serialized transaction across all connections in the
rdoConnections collection. But these transactions are not atomic — that is, operations executed against one rdoConnection could complete, but those against another might not. In this case,
the committed operations are not rolled back. Because of this, their success or failure is not interdependent.

Because the rdoEnvironment object determines transaction scope in your application, committing an rdoEnvironment transaction commits all pending transactions on all open rdoConnection
databases (which are opened on that rdoEnvironment object and their corresponding open rdoResultset objects). This does not imply a two-phase commit operation. It simply means that
individual rdoConnection objects are instructed to commit any pending transactions — one at a time.

Note The ODBC transaction model does not support nested transactions. That is, you cannot execute a second BeginTrans method before the previous transaction is either committed or
rolled back. However, if your ODBC data source supports it, you can use SQL statements to execute nested transactions. This is supported by all Microsoft SQL Server systems.

When you use ODBC transactions, transactions do not span connections: Transactions begun and committed on one connection do not affect transactions pending on other connections, even if
both connections are made to the same server and database.

Trapping rdoEnvironment Transaction Events

The rdoEnvironment object fires an event whenever a transaction operation has completed. These events can be used to synchronize other processes with the transaction state. Basically, the
BeginTrans, CommitTrans, and RollbackTrans event fire after the corresponding method has fired.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRdoEnvironmentObjectToManageTransactions.asp (1 of 2) [11/17/2002 11:35:50 PM]


Welcome to the MSDN Library
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRdoEnvironmentObjectToManageTransactions.asp (2 of 2) [11/17/2002 11:35:50 PM]


Managing Connections with the rdoEnvironment Object

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Creating an rdoEnvironment Object

Visual Basic Concepts

Managing Connections with the rdoEnvironment Object

See Also

You can use the rdoEnvironment object's OpenConnection method to open connections to the data source and create rdoConnection objects to manage and reference these connections. In an
rdoEnvironment, you can open multiple connections (each accessing its own database), manage transactions, and establish security based on user names and passwords. For example, you can:

● Create an rdoEnvironment object using the Name, Password, and UserName properties to establish a named, password-protected environment. The environment creates a scope in which you can open multiple connections and manage multiple ODBC transactions.

● Use the OpenConnection method to establish one or more connections in that rdoEnvironment.

● Use the BeginTrans, CommitTrans, and RollbackTrans methods to manage ODBC transaction processing within an rdoEnvironment.
● Use several rdoEnvironment objects to conduct multiple, simultaneous, independent, and overlapping transactions.

● Use the Dim X as New rdoConnection to create a stand-alone rdoConnection object and use the Add method to append it to the rdoConnections collection of an rdoEnvironment object.

● Use the Remove method to remove a specified rdoConnection object from its parent rdoConnections collection.

● Use the Close method to terminate an environment and the connection.

Note It is no longer always necessary to reference the rdoEnvironment object because rdoConnection objects can be created as stand-alone objects.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html...ngConnectionsWithRdoEnvironmentObject.asp?frame=true [11/17/2002 11:35:54 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Creating an rdoEnvironment Object

MSDN Library GO
Advanced Search Visual Basic Concepts

Managing Connections with the rdoEnvironment Object

See Also

Up One Level You can use the rdoEnvironment object's OpenConnection method to open connections to the data source and create rdoConnection objects to manage and reference these connections. In an
rdoEnvironment, you can open multiple connections (each accessing its own database), manage transactions, and establish security based on user names and passwords. For example, you
Using the rdoEnvironment Object to Manage Transactions can:

Managing Connections with the rdoEnvironment Object


● Create an rdoEnvironment object using the Name, Password, and UserName properties to establish a named, password-protected environment. The environment creates a scope in which you can open multiple connections and manage multiple ODBC
transactions.

● Use the OpenConnection method to establish one or more connections in that rdoEnvironment.

● Use the BeginTrans, CommitTrans, and RollbackTrans methods to manage ODBC transaction processing within an rdoEnvironment.
● Use several rdoEnvironment objects to conduct multiple, simultaneous, independent, and overlapping transactions.

● Use the Dim X as New rdoConnection to create a stand-alone rdoConnection object and use the Add method to append it to the rdoConnections collection of an rdoEnvironment object.

● Use the Remove method to remove a specified rdoConnection object from its parent rdoConnections collection.

● Use the Close method to terminate an environment and the connection.

Note It is no longer always necessary to reference the rdoEnvironment object because rdoConnection objects can be created as stand-alone objects.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconManagingConnectionsWithRdoEnvironmentObject.asp [11/17/2002 11:35:57 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control

MSDN Library GO
Advanced Search Visual Basic Concepts

Establishing an RDO Connection

See Also

Up One Level Before you can reference the data in a remote database, you must establish a connection to the data source. The source could be a remote database server, like SQL Server or Oracle, or
another database that has a suitable ODBC driver.
Providing Connection Information to RDO
Using a Registered Data Source Name (DSN) There are a number of ways to establish connections with RDO, as described in the following topics. However, unlike DAO, RDO does not manage connections for your application — it simply
Creating DSN-less RDO Connections collects parameters to be passed to the SQLDriverConnect function and calls the SQLDisconnect function to close the connection. RDO does not cache connections or attempt to share them
based on similar DSN entries. When you use the RDO Close method to close a connection, it is closed immediately.
Setting rdoConnection Options
Using rdoConnection Object Events When you are ready to open a connection, the options available to you are as follows:
Opening Connections Asynchronously
Working with Stand-Alone rdoConnection Objects ● Use the RemoteData Control to establish a connection based on its properties and create an rdoConnection object as referenced by its Connection property.

Using an rdoConnection Object ●


Declare an rdoConnection object and use the rdoEnvironment object's OpenConnection method.

Create a stand-alone rdoConnection object using the Dim x As New syntax, set its properties, and use the EstablishConnection method.

Failing to Connect to an RDO Data Source ● Use the EstablishConnection on an existing rdoConnection object after having either created a stand-alone rdoConnection object, or after having used the Close method on an existing rdoConnection object.

Using the rdoTable Object


Each of these techniques is designed to address specific programming requirements. For example, in situations where you need to submit the same query to a number of remote databases,
Closing Unneeded RDO Connections you might choose to create a stand-alone rdoConnection object that can be assigned to a number of rdoQuery objects via the ActiveConnection property. In other situations, you might prefer
the simplicity of the RemoteData control.

All of these techniques establish a physical link to a data source, like a specific SQL Server or Oracle database server. To establish a connection, you must provide the network location of the
data source, the driver type, and a number of optional parameters used to identify the user to the data source.

Once you have established a connection, you can use it to:

● Execute a query that returns one or more result sets using the OpenResultset method.

● Execute an action query using the Execute method.

● Create an rdoQuery object to subsequently execute a parameter query or stored procedure.

● Define a query that exposes one or more stored procedures as methods of the rdoConnection object.

● Associate the rdoConnection object with a specific rdoResultset object by setting the ActiveConnection property.

● Add the rdoConnection object to a chosen rdoConnections collection by using the Add method.

● Remove an rdoConnection object from its parent rdoConnections collection using the Remove method.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconEstablishingRdoConnection.asp [11/17/2002 11:46:05 PM]


Providing Connection Strings to RDO

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

Visual Basic Concepts

Providing Connection Strings to RDO

See Also

In order to tell the ODBC Driver Manager which driver to use and to tell the selected driver which data source to use, your code must provide a number of arguments in the form of a connect
string or RemoteData Control property settings. In most cases, a connect string is used to direct RDO to a specific server, database, and user.

The connect string contains a series of semi-colon delimited arguments as defined by the ODBC interface — including the ODBC driver itself. That is, all ODBC drivers have specific argument
requirements so you should consult the documentation included with the driver for specific information. This connect string is passed to the ODBC API SQLDriverConnect function along with the
hEnv for the associated rdoEnvironment object.

Note If you are converting existing DAO or ODBCDirect code, be sure to remove the ODBC argument from the front of the connect string. In addition, the LOGINTIMEOUT argument is not
supported — you have to use the LoginTimeout property of the rdoEnvironment object instead.

Generally, the connect string arguments include, but are not limited to, the following:

ODBC Connect Strings

ODBC connect string arguments What the argument specifies

DSN= Registered ODBC Data Source Name. The DSN keyword is not used if DRIVER is used.

UID= User name as established on the server. In SQL Server this is the logon name.

PWD= Password that corresponds with the logon name.

DATABASE= Requested default database (optional).

SERVER= The network name of the data source server. On a Microsoft Windows NT computer, "(local)" can be entered as the server. In this case, a local copy of SQL Server can be used, even
when this is a non-networked version.

DRIVER= Name of data source driver. Microsoft SQL Server uses {SQL Server. The DRIVER keyword is not used if DSN is used.

APP= The name of the application (optional).

WSID= The workstation ID. Typically, this is the network name of the computer on which the application resides (optional).

LANGUAGE= The national language to be used by SQL Server (optional).

Note Some of these arguments are specific to SQL Server. For Oracle or other ODBC data sources, other arguments might be required or optional.

What's Not in the Connect String

Note that the connect string does not include arguments to set the following options:

Option Default behavior

Network Address Not needed. Handled by server name.

Network Protocol Defaults to Named Pipes on SQL Server drivers.

OEMTOANSI switch Defaults to "Off"

Use Trusted Connection Option Defaults to "Off"

Generate Stored Procedure for Prepared Statement Defaults to "Off"

All of these and other driver-dependent options are set in the Data Source Name dialog launched from the Windows Control Panel. Unless you use a DSN to establish your connection, you must
accept the default settings for each of these arguments.

Providing the User ID and Password Values

To gain access to most ODBC data sources, you must provide a valid User ID and corresponding password. These values are initially registered by the system administrator but can be changed by

http://msdn.microsoft.com/library/en-us/vbcon98/h...rovidingConnectionInformationToRDO.asp?frame=true (1 of 2) [11/17/2002 11:47:58 PM]


Providing Connection Strings to RDO

your application. By setting appropriate prompt arguments of the OpenConnection or EstablishConnection methods, you can simply prompt the user for these values. However, this approach often
leads to security problems because users are permitted any number of attempts to enter a correct user ID/password combination.

Another approach uses a special User ID and password assigned specifically to your application. This technique assumes that access to the application is limited to specific users who have
permission to access the data source or workstation.

If you choose to use domain-managed security, you should use empty arguments for the UID and PWD parameters of the OpenConnection or EstablishConnection connect argument. This type of
security passes your Windows NT logon ID and password to the data source. These values are collected from the user when they log in to Windows 95 (or later) or Windows NT. If your database
administrator has implemented integrated or mixed security, this technique should permit you to log on to the data source — assuming you have been granted permission to do so. For example,
using the preceding sample code, a domain-managed security connect argument is coded as follows:

Conn$ = "DSN=MyRemote;UID=;PWD=;"

Specifying the Default Database

The database associated with an rdoConnection object is determined initially by the DATABASE connect string argument. If this is not supplied, the default database assigned to the user by the
server administrator or specified in the DSN is used.

You can also change the default database after the connection is made by executing a Transact SQL (TSQL) USE database query. In any case, you must have permission to access the selected
database. If this permission is denied, a trappable error is raised.

For example, the following code changes the default database to "Pubs" on the cn connection:

cn.Execute "Use Pubs"

Passing the Connect String to RDO or the RemoteData Control

Once complete, the connect string is passed as one of the following:

● The Connect argument of the OpenDatabase method.

● The Connect property of the RemoteData Control.

● The Connect property of the rdoConnection object when used with the EstablishConnection method.

The RemoteData control provides several specific properties to pass this information to RDO, but they are not needed if a connect string is passed in the RemoteData control Connect property.
Values provided in the connect string override values provided in RemoteData control properties.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/h...rovidingConnectionInformationToRDO.asp?frame=true (2 of 2) [11/17/2002 11:47:58 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

MSDN Library GO
Advanced Search Visual Basic Concepts

Providing Connection Strings to RDO

See Also

Up One Level In order to tell the ODBC Driver Manager which driver to use and to tell the selected driver which data source to use, your code must provide a number of arguments in the form of a connect
string or RemoteData Control property settings. In most cases, a connect string is used to direct RDO to a specific server, database, and user.
Providing Connection Information to RDO
Using a Registered Data Source Name (DSN) The connect string contains a series of semi-colon delimited arguments as defined by the ODBC interface — including the ODBC driver itself. That is, all ODBC drivers have specific argument
Creating DSN-less RDO Connections requirements so you should consult the documentation included with the driver for specific information. This connect string is passed to the ODBC API SQLDriverConnect function along with the
hEnv for the associated rdoEnvironment object.
Setting rdoConnection Options
Using rdoConnection Object Events Note If you are converting existing DAO or ODBCDirect code, be sure to remove the ODBC argument from the front of the connect string. In addition, the LOGINTIMEOUT argument is not
supported — you have to use the LoginTimeout property of the rdoEnvironment object instead.
Opening Connections Asynchronously
Working with Stand-Alone rdoConnection Objects
Generally, the connect string arguments include, but are not limited to, the following:
Using an rdoConnection Object
Failing to Connect to an RDO Data Source
ODBC Connect Strings
Using the rdoTable Object
Closing Unneeded RDO Connections
ODBC connect string arguments What the argument specifies

DSN= Registered ODBC Data Source Name. The DSN keyword is not used if DRIVER is used.

UID= User name as established on the server. In SQL Server this is the logon name.

PWD= Password that corresponds with the logon name.

DATABASE= Requested default database (optional).

SERVER= The network name of the data source server. On a Microsoft Windows NT computer, "(local)" can be entered as the server. In this case, a local copy of SQL Server can be used, even
when this is a non-networked version.

DRIVER= Name of data source driver. Microsoft SQL Server uses {SQL Server. The DRIVER keyword is not used if DSN is used.

APP= The name of the application (optional).

WSID= The workstation ID. Typically, this is the network name of the computer on which the application resides (optional).

LANGUAGE= The national language to be used by SQL Server (optional).

Note Some of these arguments are specific to SQL Server. For Oracle or other ODBC data sources, other arguments might be required or optional.

What's Not in the Connect String

Note that the connect string does not include arguments to set the following options:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconProvidingConnectionInformationToRDO.asp (1 of 2) [11/17/2002 11:48:00 PM]


Welcome to the MSDN Library
Option Default behavior

Network Address Not needed. Handled by server name.

Network Protocol Defaults to Named Pipes on SQL Server drivers.

OEMTOANSI switch Defaults to "Off"

Use Trusted Connection Option Defaults to "Off"

Generate Stored Procedure for Prepared Statement Defaults to "Off"

All of these and other driver-dependent options are set in the Data Source Name dialog launched from the Windows Control Panel. Unless you use a DSN to establish your connection, you must
accept the default settings for each of these arguments.

Providing the User ID and Password Values

To gain access to most ODBC data sources, you must provide a valid User ID and corresponding password. These values are initially registered by the system administrator but can be changed
by your application. By setting appropriate prompt arguments of the OpenConnection or EstablishConnection methods, you can simply prompt the user for these values. However, this
approach often leads to security problems because users are permitted any number of attempts to enter a correct user ID/password combination.

Another approach uses a special User ID and password assigned specifically to your application. This technique assumes that access to the application is limited to specific users who have
permission to access the data source or workstation.

If you choose to use domain-managed security, you should use empty arguments for the UID and PWD parameters of the OpenConnection or EstablishConnection connect argument. This type
of security passes your Windows NT logon ID and password to the data source. These values are collected from the user when they log in to Windows 95 (or later) or Windows NT. If your
database administrator has implemented integrated or mixed security, this technique should permit you to log on to the data source — assuming you have been granted permission to do so.
For example, using the preceding sample code, a domain-managed security connect argument is coded as follows:

Conn$ = "DSN=MyRemote;UID=;PWD=;"

Specifying the Default Database

The database associated with an rdoConnection object is determined initially by the DATABASE connect string argument. If this is not supplied, the default database assigned to the user by the
server administrator or specified in the DSN is used.

You can also change the default database after the connection is made by executing a Transact SQL (TSQL) USE database query. In any case, you must have permission to access the
selected database. If this permission is denied, a trappable error is raised.

For example, the following code changes the default database to "Pubs" on the cn connection:

cn.Execute "Use Pubs"

Passing the Connect String to RDO or the RemoteData Control

Once complete, the connect string is passed as one of the following:

● The Connect argument of the OpenDatabase method.

● The Connect property of the RemoteData Control.

● The Connect property of the rdoConnection object when used with the EstablishConnection method.

The RemoteData control provides several specific properties to pass this information to RDO, but they are not needed if a connect string is passed in the RemoteData control Connect property.
Values provided in the connect string override values provided in RemoteData control properties.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconProvidingConnectionInformationToRDO.asp (2 of 2) [11/17/2002 11:48:00 PM]


Using a Registered Data Source Name (DSN)

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

Visual Basic Concepts

Using a Registered Data Source Name (DSN)

See Also

The simplest way to establish a connection is to use a registered Data Source Name (DSN) to hold information about the server. Since a DSN contains no information about the user or application,
you need to provide that information either in the connect string or by using one of the prompt options that gathers the information from the user.

DSN entries are created either through the Windows Control Panel or the rdoRegisterDataSource method. However, using the Windows Data Sources dialog box is the preferred way to create,
modify, or delete data source names. To open this dialog box, double-click 32-bit ODBC in the Windows Control Panel.

Registered DSN entries are referred to by name in the:

● OpenConnection method's dsName argument.

● Database property of the RemoteData control.

● Connect string passed to the OpenConnection method as the connect argument.

● Connect property of the rdoConnection object used with the EstablishConnection method.

● Connect property of the RemoteData control.

The connect string always takes precedence.

Note that the DSN contains a number of arguments that can only be set using ODBC API functions programmatically, using the rdoRegisterDataSource function, or using the Windows Control
Panel. These options cannot be set via connect string arguments. For example, the OEMTOANSI and NETWORK settings can't be set with connect string arguments.

You cannot use an ODBC driver that has not been installed and registered. This process is already part of the Visual Basic setup procedure but also needs to be included in your application's setup
procedure.

The following example registers a SQL Server data source named Example, on a server named SEQUEL, and then opens the database WorkDB on that server.

Private Sub RegisterDataSource()


Dim en As rdoEnvironment
Dim cnTest As rdoConnection
Dim strAttribs As String
' Build keywords string.
strAttribs = "Description=" _
& "SQL Server on server SEQUEL" _
& Chr$(13) & "OemToAnsi=No" _
& Chr$(13) & "SERVER=SEQUEL" _
& Chr$(13) & "Network=DBNMPNTW" _
& Chr$(13) & "Database=WorkDB" _
& Chr$(13) & "Address=\\SEQUEL\PIPE\SQL\QUERY"

' Create new registered DSN.


rdoEngine.rdoRegisterDataSource "Example", _
"SQL Server", True, strAttribs
' Open the database.
Set en = rdoEngine.rdoEnvironments(0)
Set cnTest = en.OpenConnection( _
dsname:="Example", _
Prompt:=rdDriverNoPrompt, _
Connect:="UID=;PWD=;")
End Sub

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/ht...conUsingRegisteredDataSourceNameDSN.asp?frame=true [11/17/2002 11:48:06 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

MSDN Library GO
Advanced Search Visual Basic Concepts

Using a Registered Data Source Name (DSN)

See Also

Up One Level The simplest way to establish a connection is to use a registered Data Source Name (DSN) to hold information about the server. Since a DSN contains no information about the user or
application, you need to provide that information either in the connect string or by using one of the prompt options that gathers the information from the user.
Providing Connection Information to RDO
Using a Registered Data Source Name (DSN) DSN entries are created either through the Windows Control Panel or the rdoRegisterDataSource method. However, using the Windows Data Sources dialog box is the preferred way to create,
Creating DSN-less RDO Connections modify, or delete data source names. To open this dialog box, double-click 32-bit ODBC in the Windows Control Panel.

Setting rdoConnection Options


Registered DSN entries are referred to by name in the:
Using rdoConnection Object Events
Opening Connections Asynchronously
OpenConnection method's dsName argument.
Working with Stand-Alone rdoConnection Objects

● Database property of the RemoteData control.

Using an rdoConnection Object ● Connect string passed to the OpenConnection method as the connect argument.

Connect property of the rdoConnection object used with the EstablishConnection method.
Failing to Connect to an RDO Data Source

● Connect property of the RemoteData control.

Using the rdoTable Object


Closing Unneeded RDO Connections The connect string always takes precedence.

Note that the DSN contains a number of arguments that can only be set using ODBC API functions programmatically, using the rdoRegisterDataSource function, or using the Windows Control
Panel. These options cannot be set via connect string arguments. For example, the OEMTOANSI and NETWORK settings can't be set with connect string arguments.

You cannot use an ODBC driver that has not been installed and registered. This process is already part of the Visual Basic setup procedure but also needs to be included in your application's
setup procedure.

The following example registers a SQL Server data source named Example, on a server named SEQUEL, and then opens the database WorkDB on that server.

Private Sub RegisterDataSource()


Dim en As rdoEnvironment
Dim cnTest As rdoConnection
Dim strAttribs As String
' Build keywords string.
strAttribs = "Description=" _
& "SQL Server on server SEQUEL" _
& Chr$(13) & "OemToAnsi=No" _
& Chr$(13) & "SERVER=SEQUEL" _
& Chr$(13) & "Network=DBNMPNTW" _
& Chr$(13) & "Database=WorkDB" _
& Chr$(13) & "Address=\\SEQUEL\PIPE\SQL\QUERY"

' Create new registered DSN.


rdoEngine.rdoRegisterDataSource "Example", _
"SQL Server", True, strAttribs
' Open the database.
Set en = rdoEngine.rdoEnvironments(0)
Set cnTest = en.OpenConnection( _
dsname:="Example", _
Prompt:=rdDriverNoPrompt, _
Connect:="UID=;PWD=;")
End Sub

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRegisteredDataSourceNameDSN.asp (1 of 2) [11/17/2002 11:48:08 PM]


Welcome to the MSDN Library

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRegisteredDataSourceNameDSN.asp (2 of 2) [11/17/2002 11:48:08 PM]


Creating DSN-less RDO Connections

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

Visual Basic Concepts

Creating DSN-less RDO Connections

See Also

Another approach to consider when establishing RDO connections is to provide all required information in the Connect argument of the OpenConnection method. This approach affords a number
of advantages:

● This can make the creation of a DSN unnecessary, which can simplify setup and installation of client applications.

● The DSN does not have to be located in the system registry, which results in faster connect times.

● You have more control of the specific server and other connection parameters, which can increase application and system security.

If you choose to use a DSN-less connection, you must include the name of the server and driver along with any other user-specific information in the connect string. However, if you choose this
option, you can only use the default OEMTOANSI (Off), NETWORK (named pipes), and other settings that can only be set when creating a DSN.

If you choose to create a DSN-less connection, you must pass a zero-length string as the dsName argument of the OpenConnection method, or the Database property of the RemoteData control.
This notifies the ODBC driver that you want to create a DSN-less connection. In addition, note that the order of the connect string arguments is significant. The DSN argument must be provided
after the SERVER and DRIVER arguments, as shown below.

The following example illustrates creation of a DSN-less connection to establish a connection to a Microsoft SQL Server database named MyServer:

Dim Cn As rdoConnection
Dim En as rdoEnvironment, Conn As String
Set En = rdoEnvironments(0)
Conn$ = "UID=Holly;PWD=Huskador;" _
& "DATABASE=MyDb;" _
& "SERVER=MyServer;" _
& "DRIVER={SQL SERVER};DSN='';"
Set Cn = En.OpenConnection(dsName:="", _
prompt:=rdDriverNoPrompt, _
connect:=Conn$)

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreatingDSNlessRDOConnections.asp?frame=true [11/17/2002 11:48:36 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating DSN-less RDO Connections

See Also

Up One Level Another approach to consider when establishing RDO connections is to provide all required information in the Connect argument of the OpenConnection method. This approach affords a
number of advantages:
Providing Connection Information to RDO
Using a Registered Data Source Name (DSN) ● This can make the creation of a DSN unnecessary, which can simplify setup and installation of client applications.

Creating DSN-less RDO Connections ● The DSN does not have to be located in the system registry, which results in faster connect times.

● You have more control of the specific server and other connection parameters, which can increase application and system security.

Setting rdoConnection Options


Using rdoConnection Object Events If you choose to use a DSN-less connection, you must include the name of the server and driver along with any other user-specific information in the connect string. However, if you choose
this option, you can only use the default OEMTOANSI (Off), NETWORK (named pipes), and other settings that can only be set when creating a DSN.
Opening Connections Asynchronously
Working with Stand-Alone rdoConnection Objects
If you choose to create a DSN-less connection, you must pass a zero-length string as the dsName argument of the OpenConnection method, or the Database property of the RemoteData
Using an rdoConnection Object control. This notifies the ODBC driver that you want to create a DSN-less connection. In addition, note that the order of the connect string arguments is significant. The DSN argument must be
provided after the SERVER and DRIVER arguments, as shown below.
Failing to Connect to an RDO Data Source
Using the rdoTable Object
The following example illustrates creation of a DSN-less connection to establish a connection to a Microsoft SQL Server database named MyServer:
Closing Unneeded RDO Connections
Dim Cn As rdoConnection
Dim En as rdoEnvironment, Conn As String
Set En = rdoEnvironments(0)
Conn$ = "UID=Holly;PWD=Huskador;" _
& "DATABASE=MyDb;" _
& "SERVER=MyServer;" _
& "DRIVER={SQL SERVER};DSN='';"
Set Cn = En.OpenConnection(dsName:="", _
prompt:=rdDriverNoPrompt, _
connect:=Conn$)

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingDSNlessRDOConnections.asp [11/17/2002 11:48:38 PM]


Setting rdoConnection Options

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

Visual Basic Concepts

Setting rdoConnection Options

See Also

Before you use the OpenConnection or EstablishConnection methods, you can set a number of properties and options that affect how the connection is made and how queries using these
connections are processed. Generally, these options are determined by rdoEnvironment properties. However, if you create a stand-alone rdoConnection, you must preset the following
rdoConnection properties with any variations from the default values before making the connection.

The following list details rdoConnection options that must be set before a connection is attempted, their default values, and what function they perform.

rdoConnection Options

rdoConnection property Default Determines

LoginTimeout 15 How many seconds to wait before abandoning the connection attempt.

CursorDriver rdUseIfNeeded Which cursor library (if any) is used for all queries associated with the rdoConnection object.

Connect "" The ODBC parameters used to make the connection — the connect string.

Name "" The DSN name to be used for the connection.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconSettingRdoConnectionOptions.asp?frame=true [11/17/2002 11:48:43 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

MSDN Library GO
Advanced Search Visual Basic Concepts

Setting rdoConnection Options

See Also

Up One Level Before you use the OpenConnection or EstablishConnection methods, you can set a number of properties and options that affect how the connection is made and how queries using these
connections are processed. Generally, these options are determined by rdoEnvironment properties. However, if you create a stand-alone rdoConnection, you must preset the following
Providing Connection Information to RDO rdoConnection properties with any variations from the default values before making the connection.

Using a Registered Data Source Name (DSN)


Creating DSN-less RDO Connections The following list details rdoConnection options that must be set before a connection is attempted, their default values, and what function they perform.

Setting rdoConnection Options


rdoConnection Options
Using rdoConnection Object Events
Opening Connections Asynchronously
Working with Stand-Alone rdoConnection Objects rdoConnection property Default Determines

Using an rdoConnection Object LoginTimeout 15 How many seconds to wait before abandoning the connection attempt.

Failing to Connect to an RDO Data Source


CursorDriver rdUseIfNeeded Which cursor library (if any) is used for all queries associated with the rdoConnection object.
Using the rdoTable Object
Closing Unneeded RDO Connections
Connect "" The ODBC parameters used to make the connection — the connect string.

Name "" The DSN name to be used for the connection.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconSettingRdoConnectionOptions.asp [11/17/2002 11:48:45 PM]


Opening Connections Asynchronously

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

Visual Basic Concepts

Opening Connections Asynchronously

See Also

In some cases, especially when working with Internet, Wide Area Network (WAN), or Remote Access Service (RAS) connections, the time required to establish a connection can increase
dramatically. While a few seconds should be enough for a typical LAN connection, a WAN might take several minutes or more to connect. There are several ways to pre-empt problems when
attempting to make these connections:

● Set the LoginTimeout property to a high-enough value to account for the delay.

● Use the rdAsyncEnable option to return control to your application before the connection is established so that the user can be informed that the connection is being attempted without blocking the application.

● Establish an event procedure to capture the Connect event instead of polling with the StillConnecting property.

● Use the BeforeConnect event to warn the user that the connection might take an exceptionally long time.

The most important aspect of these techniques is to keep the user informed and to prevent the application from blocking. If your application, through no fault of its own, seems to lock up while
attempting to establish a connection, the user will have a tendency to try to cancel the operation in any way that presents itself — including rebooting the computer.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconOpeningConnectionsAsynchronously.asp?frame=true [11/17/2002 11:48:49 PM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

MSDN Library GO
Advanced Search Visual Basic Concepts

Opening Connections Asynchronously

See Also

Up One Level In some cases, especially when working with Internet, Wide Area Network (WAN), or Remote Access Service (RAS) connections, the time required to establish a connection can increase
dramatically. While a few seconds should be enough for a typical LAN connection, a WAN might take several minutes or more to connect. There are several ways to pre-empt problems when
Providing Connection Information to RDO attempting to make these connections:

Using a Registered Data Source Name (DSN)


Creating DSN-less RDO Connections
● Set the LoginTimeout property to a high-enough value to account for the delay.

● Use the rdAsyncEnable option to return control to your application before the connection is established so that the user can be informed that the connection is being attempted without blocking the application.

Setting rdoConnection Options ● Establish an event procedure to capture the Connect event instead of polling with the StillConnecting property.

Use the BeforeConnect event to warn the user that the connection might take an exceptionally long time.
Using rdoConnection Object Events

Opening Connections Asynchronously The most important aspect of these techniques is to keep the user informed and to prevent the application from blocking. If your application, through no fault of its own, seems to lock up while
attempting to establish a connection, the user will have a tendency to try to cancel the operation in any way that presents itself — including rebooting the computer.
Working with Stand-Alone rdoConnection Objects
Using an rdoConnection Object
Failing to Connect to an RDO Data Source
Using the rdoTable Object
Closing Unneeded RDO Connections Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconOpeningConnectionsAsynchronously.asp [11/17/2002 11:48:51 PM]


Working with Stand-Alone rdoConnection Objects

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

Visual Basic Concepts

Working with Stand-Alone rdoConnection Objects

See Also

It is not necessary to create a connection using an rdoEnvironment object, because you can simply declare a free-standing rdoConnection object using the Dim As New syntax. For example, the
following code creates a stand-alone rdoConnection object named MyCn.

Dim MyCn As New rdoConnection

By using the User Connection Designer, you can also create your own Visual Basic class that inherits from the rdoConnection object to extend the object with functionality of your own design.

Once you create a stand-alone connection, you can set the Connect property of your new rdoConnection object to address a specific server, cursor driver, and other properties as described below.
Once these properties are initialized, you can use the EstablishConnection method to connect with the specified server.

For example, to create a stand-alone rdoConnection object and establish a connection to a server specified by the CustomerDB DSN, you can use the following code:

Dim MyCn As New rdoConnection


With MyCn
.Connect = "DSN=CustomerDB;DATABASE=MAILING;" _
& "UID=;PWD=;"
.CursorDriver = rdUseNone
.LoginTimeout = 5
.EstablishConnection (rdDriverNoPrompt)
End With

If you want to associate your new stand-alone rdoConnection with a specific rdoEnvironment, you must use the Add method to add it to the rdoConnections collection associated with a
selected rdoEnvironment object. For example, the following code adds the MyCn connection to the default rdoEnvironment object:

rdoEnvironments(0).rdoConnections.Add MyCn

You can remove members from the rdoEnvironments collection by using the Remove method.

For More Information See "EstablishConnection Method" in the Language Reference" for details on using stand-alone connections.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreatingPrivateRdoConnections.asp?frame=true [11/18/2002 12:06:35 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

MSDN Library GO
Advanced Search Visual Basic Concepts

Working with Stand-Alone rdoConnection Objects

See Also

Up One Level It is not necessary to create a connection using an rdoEnvironment object, because you can simply declare a free-standing rdoConnection object using the Dim As New syntax. For example,
the following code creates a stand-alone rdoConnection object named MyCn.
Providing Connection Information to RDO
Using a Registered Data Source Name (DSN) Dim MyCn As New rdoConnection
Creating DSN-less RDO Connections
Setting rdoConnection Options By using the User Connection Designer, you can also create your own Visual Basic class that inherits from the rdoConnection object to extend the object with functionality of your own design.

Using rdoConnection Object Events


Opening Connections Asynchronously Once you create a stand-alone connection, you can set the Connect property of your new rdoConnection object to address a specific server, cursor driver, and other properties as described
below. Once these properties are initialized, you can use the EstablishConnection method to connect with the specified server.
Working with Stand-Alone rdoConnection Objects
Using an rdoConnection Object For example, to create a stand-alone rdoConnection object and establish a connection to a server specified by the CustomerDB DSN, you can use the following code:
Failing to Connect to an RDO Data Source
Using the rdoTable Object Dim MyCn As New rdoConnection
Closing Unneeded RDO Connections With MyCn
.Connect = "DSN=CustomerDB;DATABASE=MAILING;" _
& "UID=;PWD=;"
.CursorDriver = rdUseNone
.LoginTimeout = 5
.EstablishConnection (rdDriverNoPrompt)
End With

If you want to associate your new stand-alone rdoConnection with a specific rdoEnvironment, you must use the Add method to add it to the rdoConnections collection associated with a
selected rdoEnvironment object. For example, the following code adds the MyCn connection to the default rdoEnvironment object:

rdoEnvironments(0).rdoConnections.Add MyCn

You can remove members from the rdoEnvironments collection by using the Remove method.

For More Information See "EstablishConnection Method" in the Language Reference" for details on using stand-alone connections.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingPrivateRdoConnections.asp [11/18/2002 12:06:39 AM]


Using an rdoConnection Object

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

Visual Basic Concepts

Using an rdoConnection Object

See Also

Once the rdoConnection object is created, you can use it to:

● Add stand-alone rdoConnection objects to a specific rdoEnvironment transaction scope by using the Add method against a selected rdoConnections collection.

● Create rdoResultset or rdoQuery objects using the OpenResultset or CreateQuery method, respectively.

● Execute action queries to update database data, modify the schema, or perform administrative functions.

● Execute stored procedures and manage their result sets, output parameters, and return values.

● Disconnect from the data source and free its resources using the Close method against the rdoConnection object.

Note that the rdoConnection object does not set the scope for transactions; this is maintained at the rdoEnvironment level. You cannot use the transaction methods like BeginTrans, CommitTrans,
or RollbackTrans against the rdoConnection object — just a specific rdoEnvironment object.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconUsingRdoConnectionObject.asp?frame=true [11/18/2002 12:06:44 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

MSDN Library GO
Advanced Search Visual Basic Concepts

Using an rdoConnection Object

See Also

Up One Level Once the rdoConnection object is created, you can use it to:

Providing Connection Information to RDO


Using a Registered Data Source Name (DSN)
● Add stand-alone rdoConnection objects to a specific rdoEnvironment transaction scope by using the Add method against a selected rdoConnections collection.

● Create rdoResultset or rdoQuery objects using the OpenResultset or CreateQuery method, respectively.

Creating DSN-less RDO Connections ● Execute action queries to update database data, modify the schema, or perform administrative functions.

Execute stored procedures and manage their result sets, output parameters, and return values.
Setting rdoConnection Options

● Disconnect from the data source and free its resources using the Close method against the rdoConnection object.

Using rdoConnection Object Events


Opening Connections Asynchronously Note that the rdoConnection object does not set the scope for transactions; this is maintained at the rdoEnvironment level. You cannot use the transaction methods like BeginTrans,
CommitTrans, or RollbackTrans against the rdoConnection object — just a specific rdoEnvironment object.
Working with Stand-Alone rdoConnection Objects
Using an rdoConnection Object
Failing to Connect to an RDO Data Source
Using the rdoTable Object
Contact Us | E-Mail this Page | MSDN Flash Newsletter
Closing Unneeded RDO Connections
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRdoConnectionObject.asp [11/18/2002 12:06:46 AM]


Failing to Connect to an RDO Data Source

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

Visual Basic Concepts

Failing to Connect to an RDO Data Source

See Also

You might be unable to establish a connection for a variety of reasons, including:

● Lack of permission on the data source or network.

● Improper network connection or permissions.

● Missing or disabled data source.

● Missing or improperly installed or registered drivers. Both ODBC and network protocol drivers must be installed and registered.

● Too many connections have already been established by your application or other applications.

● The network or remote server is down or too busy to respond before the time specified by the LoginTimeout property has expired.

For example, when connecting to Microsoft SQL Server, Oracle, or other data sources, the number of simultaneous connections permitted might be limited by license agreements, resource
constraints, or by database settings. Check with your server administrator if you suspect that all available connections are allocated.

In any case, your code should include comprehensive error handlers to deal with all of these and other contingencies that might apply to your situation. While some of these problems are due to
setup issues, some are transitory — that is, they will correct themselves once resources are freed on the remote system or the amount of LAN or WAN traffic subsides.

Errors trapped by RDO are usually returned as generic ODBC errors that tell you very little about the root cause of the errors. However, details about the errors are saved in the rdoErrors
collection. Each rdoError in the rdoErrors collection contains specific information about what went wrong. Examining the rdoError object properties can yield vital information about the specific
error, including a description string, a native error number (as would be returned by SQL Server), and other values specific to the ODBC API error management scheme.

For More Information See the Language Reference for details on the structure and properties of the rdoError object.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconFailingToConnectToRDODataSource.asp?frame=true [11/18/2002 12:06:58 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

MSDN Library GO
Advanced Search Visual Basic Concepts

Failing to Connect to an RDO Data Source

See Also

Up One Level You might be unable to establish a connection for a variety of reasons, including:

Providing Connection Information to RDO


Using a Registered Data Source Name (DSN)
● Lack of permission on the data source or network.

● Improper network connection or permissions.

Creating DSN-less RDO Connections ● Missing or disabled data source.

Missing or improperly installed or registered drivers. Both ODBC and network protocol drivers must be installed and registered.
Setting rdoConnection Options

● Too many connections have already been established by your application or other applications.

Using rdoConnection Object Events ● The network or remote server is down or too busy to respond before the time specified by the LoginTimeout property has expired.

Opening Connections Asynchronously


For example, when connecting to Microsoft SQL Server, Oracle, or other data sources, the number of simultaneous connections permitted might be limited by license agreements, resource
Working with Stand-Alone rdoConnection Objects constraints, or by database settings. Check with your server administrator if you suspect that all available connections are allocated.

Using an rdoConnection Object


Failing to Connect to an RDO Data Source In any case, your code should include comprehensive error handlers to deal with all of these and other contingencies that might apply to your situation. While some of these problems are due
to setup issues, some are transitory — that is, they will correct themselves once resources are freed on the remote system or the amount of LAN or WAN traffic subsides.
Using the rdoTable Object
Closing Unneeded RDO Connections
Errors trapped by RDO are usually returned as generic ODBC errors that tell you very little about the root cause of the errors. However, details about the errors are saved in the rdoErrors
collection. Each rdoError in the rdoErrors collection contains specific information about what went wrong. Examining the rdoError object properties can yield vital information about the specific
error, including a description string, a native error number (as would be returned by SQL Server), and other values specific to the ODBC API error management scheme.

For More Information See the Language Reference for details on the structure and properties of the rdoError object.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconFailingToConnectToRDODataSource.asp [11/18/2002 12:07:00 AM]


Using the rdoTable Object

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

Visual Basic Concepts

Using the rdoTable Object

See Also

You can use the rdoTable object to map the tables and columns of a data source or create rdoResultset objects from all rows in the table — which is not recommended with RDO. There are very
few cases where it is necessary to retrieve all rows from a database table into workstation memory. Many remote database tables are far too large to be downloaded to the workstation.

If you need to examine the table structure exposed by a data source or examine column detail, you can use the rdoTables collection. However, to improve performance, no table meta data is
requested from the data source until the rdoTables collection is referenced. Once an rdoConnection is open, you can enumerate the tables and place their names in a ListBox control, as in the
following example (which assumes that cn is an open rdoConnection):

Dim tb As rdoTable
For Each tb in cn.rdoTables
List1.AddItem tb.Name
Next

Each rdoTable object contains an rdoColumns collection that contains details about the data type and size of each column. While it is possible to create an rdoResultset against the rdoTable object,
this query can only return all of the rows and is not recommended.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconUsingRdoTableObject.asp?frame=true [11/18/2002 12:07:09 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

MSDN Library GO
Advanced Search Visual Basic Concepts

Using the rdoTable Object

See Also

Up One Level You can use the rdoTable object to map the tables and columns of a data source or create rdoResultset objects from all rows in the table — which is not recommended with RDO. There are
very few cases where it is necessary to retrieve all rows from a database table into workstation memory. Many remote database tables are far too large to be downloaded to the workstation.
Providing Connection Information to RDO
Using a Registered Data Source Name (DSN) If you need to examine the table structure exposed by a data source or examine column detail, you can use the rdoTables collection. However, to improve performance, no table meta data is
Creating DSN-less RDO Connections requested from the data source until the rdoTables collection is referenced. Once an rdoConnection is open, you can enumerate the tables and place their names in a ListBox control, as in the
following example (which assumes that cn is an open rdoConnection):
Setting rdoConnection Options
Using rdoConnection Object Events Dim tb As rdoTable
Opening Connections Asynchronously For Each tb in cn.rdoTables
List1.AddItem tb.Name
Working with Stand-Alone rdoConnection Objects Next

Using an rdoConnection Object


Each rdoTable object contains an rdoColumns collection that contains details about the data type and size of each column. While it is possible to create an rdoResultset against the rdoTable
Failing to Connect to an RDO Data Source object, this query can only return all of the rows and is not recommended.

Using the rdoTable Object


Closing Unneeded RDO Connections
Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRdoTableObject.asp [11/18/2002 12:07:11 AM]


Closing Unneeded RDO Connections

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

Visual Basic Concepts

Closing Unneeded RDO Connections

See Also

When you no longer need access to the remote server, you should consider closing the connection with the Close method. While it does not always make sense to close a connection before an
application is terminated, schemes used to maximize the number of simultaneous users connected to a system often close connections when they become idle or are no longer needed. These
applications subsequently reopen the connections as required.

When your connection is dropped, any instance-owned objects on the server are released. For example, server-side cursors or any objects created in TempDB are dropped by the server. If you
must maintain access to these objects, you cannot close your connection.

RDO does not manage connections for you in the sense that it does not cache recently closed connections in anticipation of their use at a later time. When you use the Close method to close a
connection, or the last reference to an rdoConnection object goes out of scope, the connection is closed — permanently and immediately.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconClosingRdoConnections.asp?frame=true [11/18/2002 12:07:17 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Establishing an RDO Connection

MSDN Library GO
Advanced Search Visual Basic Concepts

Closing Unneeded RDO Connections

See Also

Up One Level When you no longer need access to the remote server, you should consider closing the connection with the Close method. While it does not always make sense to close a connection before an
application is terminated, schemes used to maximize the number of simultaneous users connected to a system often close connections when they become idle or are no longer needed. These
Providing Connection Information to RDO applications subsequently reopen the connections as required.

Using a Registered Data Source Name (DSN)


Creating DSN-less RDO Connections When your connection is dropped, any instance-owned objects on the server are released. For example, server-side cursors or any objects created in TempDB are dropped by the server. If you
must maintain access to these objects, you cannot close your connection.
Setting rdoConnection Options
Using rdoConnection Object Events RDO does not manage connections for you in the sense that it does not cache recently closed connections in anticipation of their use at a later time. When you use the Close method to close a
connection, or the last reference to an rdoConnection object goes out of scope, the connection is closed — permanently and immediately.
Opening Connections Asynchronously
Working with Stand-Alone rdoConnection Objects
Using an rdoConnection Object
Failing to Connect to an RDO Data Source Contact Us | E-Mail this Page | MSDN Flash Newsletter
Using the rdoTable Object
Closing Unneeded RDO Connections © 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconClosingRdoConnections.asp [11/18/2002 12:07:19 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control

MSDN Library GO
Advanced Search Visual Basic Concepts

Using RDO to Submit Queries

See Also

Up One Level The primary reason for creating most database front-ends is to retrieve data, manipulate it, display it, and submit changes. Most of the RDO code you write involves building queries and
processing the result sets to perform these basic operations.
Creating rdoResultset Objects
Using the rdoOpenResultset Method When you need data from the remote database, you submit a query that specifically calls for a set of data rows. When it comes time to update your data, you submit more queries that pass
Coding SQL Statements along new data or changes to the remote database. If your application needs to perform administrative functions, you submit queries that contain high-level instructions to run server-side
utilities to establish new users, or run database repair or configuration procedures. In essence, all of the interactive aspects of RDO involve submitting queries. You are basically asking
Creating RDO Parameter Queries questions and working with the answers that are returned in the form of result sets.

Generally, RDO query processing can be broken down into two parts:

● Submitting a query composed of an SQL statement that describes a result set, or references a stored procedure.

● Working with the resulting rows, parameters and return values — the result sets.

Query submission involves building an SQL statement, including any needed parameters, and sending the query to the remote server for processing. When deciding how to submit your query,
you must decide what form it is to take when it is returned. Depending on the needs of your application, you should consider the following questions:

● Does your application need to scroll or browse through the data? If you must scroll, do you need to scroll in both directions?

● Will you need to update the data? If so, can you use action queries to make the changes? Does your user have permission to change data?

● How many other users will be attempting to work on the same data at the same time? Do you have control over these other applications? Will they cooperate with your data sharing scheme?

● How many rows will return from the query? Does your system have the capacity to store these rows? Does the network have the bandwidth to transmit these rows?

● How are the rows returned — as bookmarks or as static data?

● Must you pass parameters to the query?

● Does the query return rows, output parameters, or return values, or does it simply perform an action?

● Is the query likely to be repeated several times over the course of the application or executed only a few times?

The following topics address these questions to help you choose the right strategy to fetch your data in a variety of situations.

Managing RDO Queries

Once you have opened a connection, you can submit queries to the remote server for execution. No matter which technique you use, RDO will execute your queries and retrieve the result sets
with one of two ODBC API function sets as described below:

● If you use queries that are run only once, use the OpenResultset or Execute method to execute fixed SQL queries against the rdoConnection object to create rdoResultset objects or execute action queries. This option routes your queries to the ODBC API
SQLExecDirect function. You can also force the use of the SQLExecDirect function by using the rdExecDirect option with the Execute or OpenResultset methods.

● If you use queries that are run more than once and might require parameters, use the CreateQuery method to instantiate an rdoQuery object that can be reused as needed and that allows changes to one or more parameters each time the query is executed.
Once the rdoQuery is created, use the OpenResultset or Execute method against the rdoQuery to create an rdoResultset or execute an action query. To change the query parameters, change the rdoParameter object settings. This option routes your queries to
the ODBC API SQLPrepare and SQLExecute functions.

● If you use stored procedures to access data or perform action queries, you can use the User Connection Designer to link specific stored procedures and create customized rdoQuery objects to access them. This can also be done in code. This option routes your
queries to the ODBC API SQLPrepare and SQLExecute functions. Unlike DAO queries that are stored in the database, these rdoQuery objects are re-created each time your program executes.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconSubmittingQuery.asp (1 of 2) [11/18/2002 12:07:37 AM]


Welcome to the MSDN Library

Note The outdated Visual Basic version 4.0 rdoPreparedStatement object is still supported in Visual Basic version 6.0 for backward compatibility, but is not recommended for future
development. You are encouraged to replace all references to rdoPreparedStatement objects with rdoQuery objects.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconSubmittingQuery.asp (2 of 2) [11/18/2002 12:07:37 AM]


Creating rdoResultset Objects

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Submit Queries

Visual Basic Concepts

Creating rdoResultset Objects

See Also

While RDO has a number of options to make the process of retrieving result sets and returned parameters easier, all of them ultimately result in the creation of an rdoResultset object. For
example, all of the following techniques can be used to create and manage rdoResultset objects:

● Use the OpenResultset method against an rdoConnection object. This is used to submit a query that you do not expect to execute more than once in your application. The returned rows are placed in an rdoResultset object.

● Use the OpenResultset method against an rdoQuery object. This technique is used to submit a query that you expect to execute more than once in your application or that requires one or more parameters. The returned rows are placed in an rdoResultset object
and any parameters returned from the query are referenced via the rdoQuery object's rdoParameters collection.

● Create a stand-alone rdoQuery object, set its properties, and associate it with a specific connection using the ActiveConnection property. An rdoResultset object can then be created against the enabled rdoQuery using the OpenResultset method. The
ActiveConnection property can be changed to refer to a different connection and the query re-executed without having to create another rdoResultset object.

For More Information See "Creating RDO Parameter Queries" later in this chapter.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCreatingRdoResultsetObjects.asp?frame=true [11/18/2002 12:07:40 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Submit Queries

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating rdoResultset Objects

See Also

Up One Level While RDO has a number of options to make the process of retrieving result sets and returned parameters easier, all of them ultimately result in the creation of an rdoResultset object. For
example, all of the following techniques can be used to create and manage rdoResultset objects:
Creating rdoResultset Objects
Using the rdoOpenResultset Method ● Use the OpenResultset method against an rdoConnection object. This is used to submit a query that you do not expect to execute more than once in your application. The returned rows are placed in an rdoResultset object.

Coding SQL Statements ● Use the OpenResultset method against an rdoQuery object. This technique is used to submit a query that you expect to execute more than once in your application or that requires one or more parameters. The returned rows are placed in an rdoResultset
object and any parameters returned from the query are referenced via the rdoQuery object's rdoParameters collection.

Creating RDO Parameter Queries ● Create a stand-alone rdoQuery object, set its properties, and associate it with a specific connection using the ActiveConnection property. An rdoResultset object can then be created against the enabled rdoQuery using the OpenResultset method. The
ActiveConnection property can be changed to refer to a different connection and the query re-executed without having to create another rdoResultset object.

For More Information See "Creating RDO Parameter Queries" later in this chapter.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingRdoResultsetObjects.asp [11/18/2002 12:07:42 AM]


Using the rdoOpenResultset Method

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Submit Queries

Visual Basic Concepts

Using the OpenResultset Method

See Also

No matter which type of query you execute, or which type of result set you create, you must use the OpenResultset method to build an rdoResultset to fetch and navigate through the data rows.
The connection and specific cursor type used to create the rdoResultset depends on the properties of the object referenced with the OpenResultset method. For example, if you execute the
OpenResultset against the rdoQuery object, RDO uses the connection specified in its ActiveConnection property and the cursor type specified in its CursorDriver property.

The OpenResultset method accepts the following arguments:

● When you use the OpenResultset method with an rdoConnection object, you must specify the name argument — basically the name argument string specifies an SQL query. When you use OpenResultset against an rdoQuery object, the SQL statement is drawn
from the rdoQuery object's SQL property so the name argument is not needed. When OpenResultset is used against the rdoTable object, the query is assumed to include all rows from the specified table. If your SQL query needs to include parameters, see
"Creating RDO Parameter Queries" later in this chapter for more information about choosing the right SQL syntax for parameter queries.

● The type argument specifies the type of cursor — unless you have disabled cursor creation on this connection by specifying rdUseNone for the CursorDriver property. If you do not indicate a cursor type, rdOpenForwardOnly is assumed. The type argument can
also specify keyset, dynamic, static, or forward-only cursor types.

Note Not all cursor libraries are capable of implementing all cursor types. For example, the ODBC client-side cursor library (rdUseODBC) is incapable of creating keyset or dynamic cursors. When a driver is incapable of creating a cursor, the driver generally uses
a fall-back strategy that selects another cursor that it is capable of creating.

● The locktype argument specifies the type of locking used to support concurrency. Generally, this option determines how and when pages and rows are locked by the remote server. For example, using the locktype argument, you can select several types of
optimistic locking, one type of pessimistic locking, or no locking at all, as when you select rdConcurReadOnly (the default). For more information, see "OpenResultset Method" in the Language Reference".

● The options argument specifies if the query should be executed asynchronously and the ODBC function used to execute the query. By default, the query is executed synchronously and the SQLPrepare and SQLExecute API functions are used.

Choosing a Cursor Type

Using arguments of the OpenResultset method or properties of the rdoQuery object, you can specify the type of cursor (if any) and other attributes of the rdoResultset object. However, in many
cases, cursors are not the best way to retrieve data as they negatively affect performance and resource utilization.

For More Information See "OpenResultset Method," "Type Property," and "SQL Property" in the Language Reference".

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconUsingRdoOpenResultsetMethod.asp?frame=true [11/18/2002 12:07:45 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Submit Queries

MSDN Library GO
Advanced Search Visual Basic Concepts

Using the OpenResultset Method

See Also

Up One Level No matter which type of query you execute, or which type of result set you create, you must use the OpenResultset method to build an rdoResultset to fetch and navigate through the data
rows. The connection and specific cursor type used to create the rdoResultset depends on the properties of the object referenced with the OpenResultset method. For example, if you execute
Creating rdoResultset Objects the OpenResultset against the rdoQuery object, RDO uses the connection specified in its ActiveConnection property and the cursor type specified in its CursorDriver property.

Using the rdoOpenResultset Method


Coding SQL Statements The OpenResultset method accepts the following arguments:

Creating RDO Parameter Queries


● When you use the OpenResultset method with an rdoConnection object, you must specify the name argument — basically the name argument string specifies an SQL query. When you use OpenResultset against an rdoQuery object, the SQL statement is
drawn from the rdoQuery object's SQL property so the name argument is not needed. When OpenResultset is used against the rdoTable object, the query is assumed to include all rows from the specified table. If your SQL query needs to include parameters,
see "Creating RDO Parameter Queries" later in this chapter for more information about choosing the right SQL syntax for parameter queries.

● The type argument specifies the type of cursor — unless you have disabled cursor creation on this connection by specifying rdUseNone for the CursorDriver property. If you do not indicate a cursor type, rdOpenForwardOnly is assumed. The type argument
can also specify keyset, dynamic, static, or forward-only cursor types.

Note Not all cursor libraries are capable of implementing all cursor types. For example, the ODBC client-side cursor library (rdUseODBC) is incapable of creating keyset or dynamic cursors. When a driver is incapable of creating a cursor, the driver generally
uses a fall-back strategy that selects another cursor that it is capable of creating.

● The locktype argument specifies the type of locking used to support concurrency. Generally, this option determines how and when pages and rows are locked by the remote server. For example, using the locktype argument, you can select several types of
optimistic locking, one type of pessimistic locking, or no locking at all, as when you select rdConcurReadOnly (the default). For more information, see "OpenResultset Method" in the Language Reference".

● The options argument specifies if the query should be executed asynchronously and the ODBC function used to execute the query. By default, the query is executed synchronously and the SQLPrepare and SQLExecute API functions are used.

Choosing a Cursor Type

Using arguments of the OpenResultset method or properties of the rdoQuery object, you can specify the type of cursor (if any) and other attributes of the rdoResultset object. However, in
many cases, cursors are not the best way to retrieve data as they negatively affect performance and resource utilization.

For More Information See "OpenResultset Method," "Type Property," and "SQL Property" in the Language Reference".

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconUsingRdoOpenResultsetMethod.asp [11/18/2002 12:07:46 AM]


Coding SQL Statements

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Submit Queries

Visual Basic Concepts

Coding SQL Statements

See Also

The SQL property contains the structured query language statement that determines how rows are selected, grouped, and ordered when you execute a query. You can use a query to select rows
to include an rdoResultset object. You can also define action queries to modify data without returning rows.

You cannot provide a table name at design time for the SQL property of the RemoteData control — as you can when using DAO. However, you can either use a simple query like SELECT * FROM
<table>, or at run time populate the rdoTables collection and use one of the table names returned in the collection. The rdoTables collection is populated as soon as it is associated with an active
connection and referenced.

Your query's SQL syntax must conform to the SQL dialect as defined by the data source query processor. The SQL dialect supported by the ODBC interface is defined by the X/Open standard.
Generally, a driver scans an SQL statement looking for specific escape sequences that are used to identify nonstandard operands like timestamp, literals, and functions.

When you need to return rows from a query, you generally provide a SELECT statement in the SQL property. The SELECT statement specifies:

● The name of each column to return or "*" to indicate all columns of the specified tables are to be returned. Ambiguous column names must be addressed to include the table name as needed. You can also specify aggregate expressions to perform arithmetic or
other functions on the columns selected. Aggregate or computed columns must also be aliased to provide name references for them in the rdoColumns collection.

● The name of each table to be searched for the information requested. If you specify more than one table, you should provide a WHERE clause to indicate which column(s) are used to cross-reference the information in the tables. Generally, these columns have the
same name and meaning. For example the CustomerID column in the Customers table and the Orders table might be used to join the two tables on a common column.

● Optionally, a WHERE clause to specify how to join the tables specified and how to limit or filter the number and types of rows returned. You can use user-supplied parameters in the WHERE clause to specify different sets of information from query to query. If you
need to provide WHERE clause criteria at run time, you must create a parameter query.

● Optionally, other clauses such as ORDER BY to set a particular order for the rows or GROUP BY to structure the rows in related sets.

Each SQL dialect supports different syntax and different ancillary clauses. See the documentation provided with your remote server for more details.

For More Information See "Creating RDO Parameter Queries."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html/vbconCodingSQLStatements.asp?frame=true [11/18/2002 12:07:52 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Submit Queries

MSDN Library GO
Advanced Search Visual Basic Concepts

Coding SQL Statements

See Also

Up One Level The SQL property contains the structured query language statement that determines how rows are selected, grouped, and ordered when you execute a query. You can use a query to select
rows to include an rdoResultset object. You can also define action queries to modify data without returning rows.
Creating rdoResultset Objects
Using the rdoOpenResultset Method You cannot provide a table name at design time for the SQL property of the RemoteData control — as you can when using DAO. However, you can either use a simple query like SELECT *
Coding SQL Statements FROM <table>, or at run time populate the rdoTables collection and use one of the table names returned in the collection. The rdoTables collection is populated as soon as it is associated with
an active connection and referenced.
Creating RDO Parameter Queries
Your query's SQL syntax must conform to the SQL dialect as defined by the data source query processor. The SQL dialect supported by the ODBC interface is defined by the X/Open standard.
Generally, a driver scans an SQL statement looking for specific escape sequences that are used to identify nonstandard operands like timestamp, literals, and functions.

When you need to return rows from a query, you generally provide a SELECT statement in the SQL property. The SELECT statement specifies:

● The name of each column to return or "*" to indicate all columns of the specified tables are to be returned. Ambiguous column names must be addressed to include the table name as needed. You can also specify aggregate expressions to perform arithmetic
or other functions on the columns selected. Aggregate or computed columns must also be aliased to provide name references for them in the rdoColumns collection.

● The name of each table to be searched for the information requested. If you specify more than one table, you should provide a WHERE clause to indicate which column(s) are used to cross-reference the information in the tables. Generally, these columns have
the same name and meaning. For example the CustomerID column in the Customers table and the Orders table might be used to join the two tables on a common column.

● Optionally, a WHERE clause to specify how to join the tables specified and how to limit or filter the number and types of rows returned. You can use user-supplied parameters in the WHERE clause to specify different sets of information from query to query. If
you need to provide WHERE clause criteria at run time, you must create a parameter query.

● Optionally, other clauses such as ORDER BY to set a particular order for the rows or GROUP BY to structure the rows in related sets.

Each SQL dialect supports different syntax and different ancillary clauses. See the documentation provided with your remote server for more details.

For More Information See "Creating RDO Parameter Queries."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCodingSQLStatements.asp [11/18/2002 12:07:53 AM]


Creating RDO Parameter Queries

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Submit Queries

Visual Basic Concepts

Creating RDO Parameter Queries

See Also

If the SQL query you need to execute includes one or more parameters in the WHERE clause, you can use the rdoQuery object to run it and manage the parameters for each execution. This
technique is especially useful when executing queries that are run repeatedly or against a number of connections — and especially when executing parameterized stored procedures.

Tip You can also build up your own queries, concatenating the parameters together to form a complete SQL statement. In some cases, this approach might be the only way that a parameter
query can be created — especially in cases where the query is complex or uses the remote database syntax in an unusual way.

In any case, the SQL statement you submit must use the correct syntax. Many problems associated with parameter queries result from improperly coding the native SQL required by the remote
server or the ODBC SQL syntax as described below. Queries submitted with incorrect syntax can result in a variety of problems, including syntax errors returned from the remote engine or RDO's
inability to create the rdoParameters collection.

Managing Parameters with the rdoParameters Collection

When you want RDO to manage the parameters for you using the rdoParameters collection, you include a question mark for each parameter in your SQL statement. The "?" acts as a placeholder
for input, output, and input/output query parameters; your code indicates which is which by setting the Direction property. RDO and the ODBC interface automatically manage these parameters
and bind each to an rdoParameter object with a predefined data type. In some cases, your code might have to force a specific data type for certain parameters. This is especially true when your
query contains a expression whose arguments are passed as parameters.

When all parameters have been marked and identified, RDO and the ODBC interface automatically create a driver-specific SQL statement and an rdoParameters collection to manage the individual
parameter values and data types. For the most part, you do not have to worry about quoting strings used as arguments or other special formatting.

Note When the rdoQuery object is created, no check is made for proper syntax. It is only when the query is executed or the rdoParameters collection is accessed that the query is compiled and
its parameters evaluated. If the statement is not coded correctly, you can trigger a trappable 40054 "Invalid parameter was passed" error, or some other ODBC error. In some cases, the
rdoParameters collection is not created, so when it is referenced, you might get a trappable error indicating that the object does not exist.

Tip While you might have discovered ODBC drivers for DAO (Access) databases in your list of available ODBC drivers, they are not ODBC Level II compliant. You can use RDO to submit queries
and return result sets from this driver, but it is incapable of creating rdoParameter objects or managing query parameters as supported by Level II compliant drivers.

Choosing the Right SQL Syntax for Parameter Queries

When coding the SQL property of an rdoQuery object or the name argument of the OpenResultset method, you can choose between one of three syntax styles to code your parameter query:

● Concatenated Strings. Your code builds up the SQL statement and its parameters using the Visual Basic concatenation (&) operator. This statement can be passed to the name argument of the OpenResultset method or the rdoQuery object's SQL property. A
concatenated string parameter query might look like this:

sSQL = "Select Name, Age From Animals " _


& " Where Weight > " & WeightWanted.Text _
& " and Type = '" & TypeWanted.Text & "'"

● Native SQL syntax. The SQL syntax used by the remote server. You can execute your own query or stored procedure and pass in parameters by concatenation, placeholders, or both. The parameters marked with placeholders are managed by RDO as
rdoParameter objects. A SQL parameter query might look like this:

sSQL = "Select AU_LName from Authors" _


& " Where AU_Fname = ?"

– or –

sSQL = "Execute MyStoredProc 'Arg1', 450, '" _


& Text1 & "'"

– or –

sSQL = "Execute MyStoredProc ?, ?, ?"

● ODBC CALL syntax. Designed to call stored procedures that return a return status or output parameters. A placeholder can be defined for each input, output, or input/output parameter; the placeholders are automatically mapped to rdoParameter objects. You
can also mix in concatenated operators as needed. An ODBC CALL parameter query might look like this:

sSQL = "{call ParameterTest (?,?,?) }"

– or –

sSQL = "{? = call ParameterTest (?,?,?) }"

http://msdn.microsoft.com/library/en-us/vbcon98/.../vbconCreatingRDOParameterQueries.asp?frame=true (1 of 3) [11/18/2002 12:07:57 AM]


Creating RDO Parameter Queries

– or –

sSQL = "{? = call CountAnimals (?, ?, 14, 'Pig')}

Note The SQL Server ODBC driver requires that all nonbound parameters (the parameters you concatenate into the query in code) appear to the right of all placeholder parameters (those
marked with a ?). If they don't, a trappable error occurs indicating "Wrong number of parameters."

Benefits and Limitations of the ODBC CALL Syntax

There are a number of benefits to using the ODBC CALL syntax. For instance, ODBC uses an Open Data Systems Remote Procedure Call (ODS RPC) to perform the query. The parameters are
passed in their native format and don't have to be parsed or converted into other data types. It also means that ODBC does not have to "prepare" the query for processing, as it already exists in
the form of a stored procedure on the remote server. This makes these calls more efficient and allows for better portability across databases.

Using rdExecDirect with Parameter Queries

The rdExecDirect option forces RDO to use the ODBC API SQLExecDirect function when executing the procedure. This bypasses the ODBC API SQLPrepare step, which is used to create a temporary
procedure to execute the query. This option can be used in situations where the SQL syntax required is acceptable to the remote server but unacceptable to the ODBC interface. However, when
executing a stored procedure parameter query, you should not use the rdExecDirect option because it prevents proper type binding of the parameters.

Note In some cases, the temporary stored procedures created by the ODBC interface might not be removed until the connection is closed. Using the rdExecDirect option can eliminate this
problem.

Summarizing the Syntax Options

The following table summarizes the options available when using each of the three syntax styles:

Syntax Options

Feature Native SQL syntax ODBC Call syntax Concatenated strings

Can pass native SQL that does not reference a stored procedure Yes No Yes

Can execute stored procedures Yes Yes Yes

Can use ? placeholders for parameters Yes Yes No

Manage return value No Yes No

Manage output arguments No Yes No

SQL statement can include multiple Select statements? Yes No Yes

Note RDO's ability to manage the parameters of your query in the RDO parameters collection is gated by the ODBC interface's ability to correctly parse the query and determine correct data
types for each parameter. In some cases, it is impossible for the ODBC driver manager to properly identify each parameter of an SQL statement. In these cases, converting the statement into a
stored procedure, even temporarily, might enable an otherwise unusable query.

Tip While the ODBC Call syntax can be used in situations where you pass no arguments, or have no returned arguments, you should generally use the it when you need to capture the stored
procedure return status and output arguments.

Coding a Typical Parameter Query

A parameter query simply substitutes user-supplied or application-supplied parameters into an ordinary query. While this query is usually a SELECT statement, it could be an INSERT, UPDATE, or
DELETE query as well. The following example illustrates how to code a simple SELECT query with a single parameter. The query looks up authors by name from the Pubs sample database.

First, set up an SQL query that marks each parameter using the ? parameter marker.

QSQL$ = "SELECT * FROM Authors WHERE Au_Lname = ?"

Next, create an rdoQuery object to manage the query and its parameters.

Set PSAuthors = cn.CreateQuery("",QSQL$)

Next, use the following code to insert the value entered by the user (Text1.Text) into the query.

PSAuthors.rdoParameters(0) = Text1.Text

http://msdn.microsoft.com/library/en-us/vbcon98/.../vbconCreatingRDOParameterQueries.asp?frame=true (2 of 3) [11/18/2002 12:07:57 AM]


Creating RDO Parameter Queries

Note that the rdoParameters object can be implied here, as it is the default collection of the rdoQuery object. The equivalent code would be:

PSAuthors(0) = Text1.Text

Next, create an rdoResultset to fetch the qualifying rows (those whose last name match the parameter value).

Set MyRs = CpwPSAuthors.OpenResultset()

If the user changes the parameter value in Text1.Text, you can re-apply the new parameter and re-execute the query by using the Requery method against the rdoResultset(MyRs) without
having to rebuild the rdoQuery object.

PSAuthors(0) = Text1.Text
MyRs.Requery

When RDO executes the Requery method, it refreshes the parameter value(s) in the rdoParameters collection bound to the query parameters, flushes the current result set, sends the query to the
data source for execution, and creates a new rdoResultset.

Keep in mind that when the query is first created, RDO and the ODBC layers create a temporary stored procedure on the remote server designed to accept the parameters. Each time the query is
executed, this temporary query is simply passed the new argument(s) and executed.

Tip If you used the rdAsyncEnable option with the OpenResultset method, use it also with the Requery method.

Note When executing stored procedures that do not require parameters, do not include the parenthesis in the SQL statement. For example, to execute the "MySP" procedure, which takes no
parameters, use the following syntax:

{Call MySP }

If the user changes the parameter value, you can re-apply the parameter value and re-execute the query by using the Requery method against the rdoResultset (MyRs).

Cpw(0) = Text1.Text
MyRs.Requery

Concatenating Parameters

You can also specify parameters in any SQL query by concatenating the parameters to the SQL statement string. For example, to submit a query using this technique, you can use the following
code:

QSQL = "SELECT * FROM Authors WHERE Au_Lname = '" _


& Text.Text & "'"
Set MyRs = Cn.OpenResultSet(QSQL)

In this case, the rdoParameters collection is not created and cannot be referenced. To change the query parameter, you must rebuild the SQL statement with the new parameter value each time
the query is executed or before you use the Requery method. In addition, unless you use the rdExecDirect option, RDO creates a new temporary stored procedure to execute the query each time
you use the OpenResultset method.

For More Information See "rdoQuery Object," "rdoParameter Object," "Requery Method," and "OpenResultset Method" in the Language Reference". For additional information on stored
procedures, see "Using RDO to Execute Stored Procedures."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/.../vbconCreatingRDOParameterQueries.asp?frame=true (3 of 3) [11/18/2002 12:07:57 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Submit Queries

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating RDO Parameter Queries

See Also

Up One Level If the SQL query you need to execute includes one or more parameters in the WHERE clause, you can use the rdoQuery object to run it and manage the parameters for each execution. This
technique is especially useful when executing queries that are run repeatedly or against a number of connections — and especially when executing parameterized stored procedures.
Creating rdoResultset Objects
Using the rdoOpenResultset Method Tip You can also build up your own queries, concatenating the parameters together to form a complete SQL statement. In some cases, this approach might be the only way that a parameter
Coding SQL Statements query can be created — especially in cases where the query is complex or uses the remote database syntax in an unusual way.

Creating RDO Parameter Queries


In any case, the SQL statement you submit must use the correct syntax. Many problems associated with parameter queries result from improperly coding the native SQL required by the remote
server or the ODBC SQL syntax as described below. Queries submitted with incorrect syntax can result in a variety of problems, including syntax errors returned from the remote engine or
RDO's inability to create the rdoParameters collection.

Managing Parameters with the rdoParameters Collection

When you want RDO to manage the parameters for you using the rdoParameters collection, you include a question mark for each parameter in your SQL statement. The "?" acts as a
placeholder for input, output, and input/output query parameters; your code indicates which is which by setting the Direction property. RDO and the ODBC interface automatically manage
these parameters and bind each to an rdoParameter object with a predefined data type. In some cases, your code might have to force a specific data type for certain parameters. This is
especially true when your query contains a expression whose arguments are passed as parameters.

When all parameters have been marked and identified, RDO and the ODBC interface automatically create a driver-specific SQL statement and an rdoParameters collection to manage the
individual parameter values and data types. For the most part, you do not have to worry about quoting strings used as arguments or other special formatting.

Note When the rdoQuery object is created, no check is made for proper syntax. It is only when the query is executed or the rdoParameters collection is accessed that the query is compiled
and its parameters evaluated. If the statement is not coded correctly, you can trigger a trappable 40054 "Invalid parameter was passed" error, or some other ODBC error. In some cases, the
rdoParameters collection is not created, so when it is referenced, you might get a trappable error indicating that the object does not exist.

Tip While you might have discovered ODBC drivers for DAO (Access) databases in your list of available ODBC drivers, they are not ODBC Level II compliant. You can use RDO to submit
queries and return result sets from this driver, but it is incapable of creating rdoParameter objects or managing query parameters as supported by Level II compliant drivers.

Choosing the Right SQL Syntax for Parameter Queries

When coding the SQL property of an rdoQuery object or the name argument of the OpenResultset method, you can choose between one of three syntax styles to code your parameter query:

● Concatenated Strings. Your code builds up the SQL statement and its parameters using the Visual Basic concatenation (&) operator. This statement can be passed to the name argument of the OpenResultset method or the rdoQuery object's SQL property.
A concatenated string parameter query might look like this:

sSQL = "Select Name, Age From Animals " _


& " Where Weight > " & WeightWanted.Text _
& " and Type = '" & TypeWanted.Text & "'"

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingRDOParameterQueries.asp (1 of 4) [11/18/2002 12:08:00 AM]


Welcome to the MSDN Library

● Native SQL syntax. The SQL syntax used by the remote server. You can execute your own query or stored procedure and pass in parameters by concatenation, placeholders, or both. The parameters marked with placeholders are managed by RDO as
rdoParameter objects. A SQL parameter query might look like this:

sSQL = "Select AU_LName from Authors" _


& " Where AU_Fname = ?"

– or –

sSQL = "Execute MyStoredProc 'Arg1', 450, '" _


& Text1 & "'"

– or –

sSQL = "Execute MyStoredProc ?, ?, ?"

● ODBC CALL syntax. Designed to call stored procedures that return a return status or output parameters. A placeholder can be defined for each input, output, or input/output parameter; the placeholders are automatically mapped to rdoParameter objects.
You can also mix in concatenated operators as needed. An ODBC CALL parameter query might look like this:

sSQL = "{call ParameterTest (?,?,?) }"

– or –

sSQL = "{? = call ParameterTest (?,?,?) }"

– or –

sSQL = "{? = call CountAnimals (?, ?, 14, 'Pig')}

Note The SQL Server ODBC driver requires that all nonbound parameters (the parameters you concatenate into the query in code) appear to the right of all placeholder parameters (those
marked with a ?). If they don't, a trappable error occurs indicating "Wrong number of parameters."

Benefits and Limitations of the ODBC CALL Syntax

There are a number of benefits to using the ODBC CALL syntax. For instance, ODBC uses an Open Data Systems Remote Procedure Call (ODS RPC) to perform the query. The parameters are
passed in their native format and don't have to be parsed or converted into other data types. It also means that ODBC does not have to "prepare" the query for processing, as it already exists
in the form of a stored procedure on the remote server. This makes these calls more efficient and allows for better portability across databases.

Using rdExecDirect with Parameter Queries

The rdExecDirect option forces RDO to use the ODBC API SQLExecDirect function when executing the procedure. This bypasses the ODBC API SQLPrepare step, which is used to create a
temporary procedure to execute the query. This option can be used in situations where the SQL syntax required is acceptable to the remote server but unacceptable to the ODBC interface.
However, when executing a stored procedure parameter query, you should not use the rdExecDirect option because it prevents proper type binding of the parameters.

Note In some cases, the temporary stored procedures created by the ODBC interface might not be removed until the connection is closed. Using the rdExecDirect option can eliminate this
problem.

Summarizing the Syntax Options

The following table summarizes the options available when using each of the three syntax styles:

Syntax Options

Feature Native SQL syntax ODBC Call syntax Concatenated strings

Can pass native SQL that does not reference a stored procedure Yes No Yes

Can execute stored procedures Yes Yes Yes

Can use ? placeholders for parameters Yes Yes No

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingRDOParameterQueries.asp (2 of 4) [11/18/2002 12:08:00 AM]


Welcome to the MSDN Library
Manage return value No Yes No

Manage output arguments No Yes No

SQL statement can include multiple Select statements? Yes No Yes

Note RDO's ability to manage the parameters of your query in the RDO parameters collection is gated by the ODBC interface's ability to correctly parse the query and determine correct data
types for each parameter. In some cases, it is impossible for the ODBC driver manager to properly identify each parameter of an SQL statement. In these cases, converting the statement into a
stored procedure, even temporarily, might enable an otherwise unusable query.

Tip While the ODBC Call syntax can be used in situations where you pass no arguments, or have no returned arguments, you should generally use the it when you need to capture the stored
procedure return status and output arguments.

Coding a Typical Parameter Query

A parameter query simply substitutes user-supplied or application-supplied parameters into an ordinary query. While this query is usually a SELECT statement, it could be an INSERT, UPDATE,
or DELETE query as well. The following example illustrates how to code a simple SELECT query with a single parameter. The query looks up authors by name from the Pubs sample database.

First, set up an SQL query that marks each parameter using the ? parameter marker.

QSQL$ = "SELECT * FROM Authors WHERE Au_Lname = ?"

Next, create an rdoQuery object to manage the query and its parameters.

Set PSAuthors = cn.CreateQuery("",QSQL$)

Next, use the following code to insert the value entered by the user (Text1.Text) into the query.

PSAuthors.rdoParameters(0) = Text1.Text

Note that the rdoParameters object can be implied here, as it is the default collection of the rdoQuery object. The equivalent code would be:

PSAuthors(0) = Text1.Text

Next, create an rdoResultset to fetch the qualifying rows (those whose last name match the parameter value).

Set MyRs = CpwPSAuthors.OpenResultset()

If the user changes the parameter value in Text1.Text, you can re-apply the new parameter and re-execute the query by using the Requery method against the rdoResultset(MyRs) without
having to rebuild the rdoQuery object.

PSAuthors(0) = Text1.Text
MyRs.Requery

When RDO executes the Requery method, it refreshes the parameter value(s) in the rdoParameters collection bound to the query parameters, flushes the current result set, sends the query to
the data source for execution, and creates a new rdoResultset.

Keep in mind that when the query is first created, RDO and the ODBC layers create a temporary stored procedure on the remote server designed to accept the parameters. Each time the query
is executed, this temporary query is simply passed the new argument(s) and executed.

Tip If you used the rdAsyncEnable option with the OpenResultset method, use it also with the Requery method.

Note When executing stored procedures that do not require parameters, do not include the parenthesis in the SQL statement. For example, to execute the "MySP" procedure, which takes no
parameters, use the following syntax:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingRDOParameterQueries.asp (3 of 4) [11/18/2002 12:08:00 AM]


Welcome to the MSDN Library

{Call MySP }

If the user changes the parameter value, you can re-apply the parameter value and re-execute the query by using the Requery method against the rdoResultset (MyRs).

Cpw(0) = Text1.Text
MyRs.Requery

Concatenating Parameters

You can also specify parameters in any SQL query by concatenating the parameters to the SQL statement string. For example, to submit a query using this technique, you can use the following
code:

QSQL = "SELECT * FROM Authors WHERE Au_Lname = '" _


& Text.Text & "'"
Set MyRs = Cn.OpenResultSet(QSQL)

In this case, the rdoParameters collection is not created and cannot be referenced. To change the query parameter, you must rebuild the SQL statement with the new parameter value each
time the query is executed or before you use the Requery method. In addition, unless you use the rdExecDirect option, RDO creates a new temporary stored procedure to execute the query
each time you use the OpenResultset method.

For More Information See "rdoQuery Object," "rdoParameter Object," "Requery Method," and "OpenResultset Method" in the Language Reference". For additional information on stored
procedures, see "Using RDO to Execute Stored Procedures."

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingRDOParameterQueries.asp (4 of 4) [11/18/2002 12:08:00 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control

MSDN Library GO
Advanced Search Visual Basic Concepts

Using RDO to Execute Stored Procedures

See Also

Up One Level Stored procedures are one of the most effective ways to manage and protect complex relational databases. They play a vital role in systems that support large databases, large numbers of
users, or both. Using stored procedures, you can protect critical data from random access, those with malicious intent, and those with innocent intent but destructive tendencies. In many sites,
Coding a Typical Stored Procedure with RDO stored procedures are the only way to access or update data — access to base tables is strictly prohibited.

Capturing Stored Procedure Output Parameters


One of the most powerful and important features of RDO is its ability to execute and manage the results returned by stored procedures, regardless of their complexity. The following topics
discuss how to best use this feature.

Stored procedures usually require one or more parameters, and while some stored procedures return rows, not all do. RDO provides a number of ways to handle these variations; however, if
you must capture the stored procedure return status or output parameters, you must use the ODBC CALL syntax as described in "Creating RDO Parameter Queries."

A stored procedure can return any number of result sets — and stored procedures can invoke other stored procedures. Your code needs to be prepared to manage all of these result sets, some
containing rows, some just returning parameters, some returning only the number of rows affected, and some all three.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconExecutingStoredProceduresWithRDO.asp [11/18/2002 12:08:28 AM]


Coding a Typical Stored Procedure with RDO

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Execute Stored Procedures

Visual Basic Concepts

Coding a Typical Stored Procedure with RDO

See Also

This example walks you through the steps needed to execute a stored procedure that takes two parameters. Stored procedure parameters can be input, output, or both input and output. In most
cases, the ODBC driver can automatically determine the type of parameter and correctly assign it to the Direction property. Our example executes the sp_password procedure, which can be used
in SQL Server systems to change a user’s password. This procedure assumes the password to be changed belongs to the current user because only the system administrator can change other
users' passwords.

This procedure query accepts two input parameters and passes back a return value. You could use the Execute method to run this query, but the return value would be lost: You would have no
easy way of telling if the password change was successful. To capture the return value and create an rdoQuery that can be used repeatedly to change the user password, write code as shown
below:

Dim CPw As rdoQuery, QSQL As String


QSQL$ = "{ ? = call sp_password (?, ?) }"

The next line of code creates the rdoQuery and names it SetPassword. The SQL property is set with the QSQL query defined above. This line only needs to be executed once. The new rdoQuery
object is automatically appended to the rdoQueries collection, where it can be recalled later.

Set CPw = cn.CreateQuery("SetPassword",QSQL$)

The next step sets the Direction property to indicate that the parameter is used for input, output, or both. The default Direction is rdParamInput, but in most cases it is unnecessary to set the
Direction property at all, because the ODBC driver can determine this value from the stored procedure's definition.

The ordinal number of the parameters is based on the order in which they appear in the SQL statement. In this case, the “0th” parameter is the return value (? = ), the “1st” is the first input
parameter, and the “2nd” is the second input parameter. As you can see, the rdoParameters collection is zero-based. The code shown below is actually referencing the rdoParameters collection,
which is the default collection for the rdoQuery object.

Cpw.rdoParameters(0).Direction = rdParamReturnValue

This next step sets the two input parameters that RDO inserts into the query when it is executed. Note that rdoParameters is the default collection and is implied in the following code.

Cpw(1) = "clyde" ' Set the first input parameter.


Cpw(2) = "framis" ' Set the second input parameter.

Once the parameter direction and values are set, you can use the Execute method to run the query if it does not return rows, or the OpenResultset method if the procedure contains one or more
SELECT statements:

Cpw.Execute()

Once the procedure is executed, you can examine the rdoParameters collection for the returned value:

If Cpw.rdoParameters(0) <> 0 Then


Msgbox "Could not change password"
End If

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/htm...nCodingTypicalStoredProcedureWithRDO.asp?frame=true [11/18/2002 12:09:05 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Execute Stored
Procedures
MSDN Library GO
Advanced Search
Visual Basic Concepts

Coding a Typical Stored Procedure with RDO

See Also

Up One Level This example walks you through the steps needed to execute a stored procedure that takes two parameters. Stored procedure parameters can be input, output, or both input and output. In
most cases, the ODBC driver can automatically determine the type of parameter and correctly assign it to the Direction property. Our example executes the sp_password procedure, which can
Coding a Typical Stored Procedure with RDO be used in SQL Server systems to change a user’s password. This procedure assumes the password to be changed belongs to the current user because only the system administrator can
change other users' passwords.
Capturing Stored Procedure Output Parameters

This procedure query accepts two input parameters and passes back a return value. You could use the Execute method to run this query, but the return value would be lost: You would have no
easy way of telling if the password change was successful. To capture the return value and create an rdoQuery that can be used repeatedly to change the user password, write code as shown
below:

Dim CPw As rdoQuery, QSQL As String


QSQL$ = "{ ? = call sp_password (?, ?) }"

The next line of code creates the rdoQuery and names it SetPassword. The SQL property is set with the QSQL query defined above. This line only needs to be executed once. The new rdoQuery
object is automatically appended to the rdoQueries collection, where it can be recalled later.

Set CPw = cn.CreateQuery("SetPassword",QSQL$)

The next step sets the Direction property to indicate that the parameter is used for input, output, or both. The default Direction is rdParamInput, but in most cases it is unnecessary to set the
Direction property at all, because the ODBC driver can determine this value from the stored procedure's definition.

The ordinal number of the parameters is based on the order in which they appear in the SQL statement. In this case, the “0th” parameter is the return value (? = ), the “1st” is the first input
parameter, and the “2nd” is the second input parameter. As you can see, the rdoParameters collection is zero-based. The code shown below is actually referencing the rdoParameters
collection, which is the default collection for the rdoQuery object.

Cpw.rdoParameters(0).Direction = rdParamReturnValue

This next step sets the two input parameters that RDO inserts into the query when it is executed. Note that rdoParameters is the default collection and is implied in the following code.

Cpw(1) = "clyde" ' Set the first input parameter.


Cpw(2) = "framis" ' Set the second input parameter.

Once the parameter direction and values are set, you can use the Execute method to run the query if it does not return rows, or the OpenResultset method if the procedure contains one or
more SELECT statements:

Cpw.Execute()

Once the procedure is executed, you can examine the rdoParameters collection for the returned value:

If Cpw.rdoParameters(0) <> 0 Then

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCodingTypicalStoredProcedureWithRDO.asp (1 of 2) [11/18/2002 12:09:07 AM]


Welcome to the MSDN Library
Msgbox "Could not change password"
End If

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCodingTypicalStoredProcedureWithRDO.asp (2 of 2) [11/18/2002 12:09:07 AM]


Capturing Stored Procedure Output Parameters

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Execute Stored Procedures

Visual Basic Concepts

Capturing Stored Procedure Output Parameters

See Also

Using the same technique used with parameter queries in SELECT statements, you can also capture the output parameters from a procedure.

To capture output parameters

1. Use ODBC escape syntax to establish placeholders for the output and input parameters and return values.

2. For ODBC data sources that don't automatically determine the direction, your code must set the Direction property of each rdoParameter object to indicate how the parameter is used.

3. For ODBC data sources that don't automatically (or correctly) determine the data type for individual parameters, your code must set the Type property of each rdoParameter object to indicate its data type.

4. Execute the query.

When the query has completed processing, retrieve the output parameter values from the rdoParameters collection.

Coding Output Parameter Stored Procedures

This example executes a stored procedure that expects two input parameters and returns two output parameters along with a return value parameter. Note that the SQL query uses ODBC syntax
in the rdoQuery, which is required if you intend to execute stored procedures that return output arguments.

Dim SQL As String, MyOutputVal1 As Variant


Dim MyOutputVal2 As Variant, MyRetValue As Variant _
rs As rdoResultset
Dim Ps As rdoQuery

' Use named arguments to open the connection.


Dim cn as New rdoConnection
With cn
.Connect = "dsn=Sequel;uid=;pwd=;database=workdb"
.EstablishConnection Prompt:=rdDriverNoPrompt
End With

' Use ODBC parameter argument syntax.


' Note each argument is identified
' with a ? character – one for the ReturnValue,
' one for each of the input arguments
' and one for each of the output arguments.

SQL = "{? = call TestOutputRS (?, ?, ?, ?) }"

' Create reusable rdoQuery.


Set Ps = cn.CreateQuery("PsTest", SQL)

' Set Parameter "direction" for each output


' and return value parameter.

Ps(0).Direction = rdParamReturnValue
Ps(3).Direction = rdParamOutput
Ps(4).Direction = rdParamOutput

' Set the input argument values.


Ps.rdoParameters(1) = "Test%"
Ps.rdoParameters(2) = 1

' Create the result set and populate the Ps values.


Set rs = Ps.OpenResultset(rdOpenStatic)

MyRetValue = Ps(0) ' The return value argument.


MyOutputVal1 = Ps(3) ' The first output parameter.
MyOutputVal2 = Ps(4) ' The second output parameter.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/en-us/vbcon98/html...turingStoredProcedureOutputParameters.asp?frame=true [11/18/2002 12:09:10 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control > Using RDO to Execute Stored
Procedures
MSDN Library GO
Advanced Search
Visual Basic Concepts

Capturing Stored Procedure Output Parameters

See Also

Up One Level Using the same technique used with parameter queries in SELECT statements, you can also capture the output parameters from a procedure.

Coding a Typical Stored Procedure with RDO


Capturing Stored Procedure Output Parameters To capture output parameters

1. Use ODBC escape syntax to establish placeholders for the output and input parameters and return values.

2. For ODBC data sources that don't automatically determine the direction, your code must set the Direction property of each rdoParameter object to indicate how the parameter is used.

3. For ODBC data sources that don't automatically (or correctly) determine the data type for individual parameters, your code must set the Type property of each rdoParameter object to indicate its data type.

4. Execute the query.

When the query has completed processing, retrieve the output parameter values from the rdoParameters collection.

Coding Output Parameter Stored Procedures

This example executes a stored procedure that expects two input parameters and returns two output parameters along with a return value parameter. Note that the SQL query uses ODBC
syntax in the rdoQuery, which is required if you intend to execute stored procedures that return output arguments.

Dim SQL As String, MyOutputVal1 As Variant


Dim MyOutputVal2 As Variant, MyRetValue As Variant _
rs As rdoResultset
Dim Ps As rdoQuery

' Use named arguments to open the connection.


Dim cn as New rdoConnection
With cn
.Connect = "dsn=Sequel;uid=;pwd=;database=workdb"
.EstablishConnection Prompt:=rdDriverNoPrompt
End With

' Use ODBC parameter argument syntax.


' Note each argument is identified
' with a ? character – one for the ReturnValue,
' one for each of the input arguments
' and one for each of the output arguments.

SQL = "{? = call TestOutputRS (?, ?, ?, ?) }"

' Create reusable rdoQuery.


Set Ps = cn.CreateQuery("PsTest", SQL)

' Set Parameter "direction" for each output


' and return value parameter.

Ps(0).Direction = rdParamReturnValue
Ps(3).Direction = rdParamOutput
Ps(4).Direction = rdParamOutput

' Set the input argument values.


Ps.rdoParameters(1) = "Test%"
Ps.rdoParameters(2) = 1

' Create the result set and populate the Ps values.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCapturingStoredProcedureOutputParameters.asp (1 of 2) [11/18/2002 12:09:12 AM]


Welcome to the MSDN Library
Set rs = Ps.OpenResultset(rdOpenStatic)

MyRetValue = Ps(0) ' The return value argument.


MyOutputVal1 = Ps(3) ' The first output parameter.
MyOutputVal2 = Ps(4) ' The second output parameter.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCapturingStoredProcedureOutputParameters.asp (2 of 2) [11/18/2002 12:09:12 AM]


Welcome to the MSDN Library

All Products | Support | Search | microsoft.com Home

MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |

Search for Welcome to the MSDN Library

MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Remote Data Objects and the RemoteData Control

MSDN Library GO
Advanced Search Visual Basic Concepts

Creating RDO Cursors

See Also

Up One Level Not all queries you create need to be returned in the form of a cursor. As a matter of fact, cursors are a particularly expensive way to fetch data and rarely used in production-class applications.
If you set the rdoDefaultCursorDriver property to rdUseNone, all result sets created by your application will be created as if you used the OpenResultset method with the rdOpenForwardOnly
Choosing an RDO Cursor Library and rdConcurReadOnly options set, and with RowsetSize set to 1. This is often the most efficient way to pass data from the remote server to your application.

Choosing an RDO Cursor Type


Running RDO Asynchronously It is also possible to create low-impact result sets that are also updatable through use of the Edit/Update methods. However, in most situations this approach is impractical because the base
tables are not directly updatable, so creating an updatable cursor is not possible. Whenever you create a result set with a stored procedure, the result set is not updatable — at least not using
Coding RDO Event Handlers the Edit/Update methods. In these cases, you can use the WillUpdateRows method to execute an action query that performs the actual update operation(s).

Using RDO Events


Regardless of how you create a cursor, you can usually update the data using one of several techniques — even if the cursor is not updatable:

● Executing a stored procedure that updates a selected row based on a code-provided key.

● Executing an action query that changes specifically addressed rows. In this case your code creates a suitable WHERE clause used in the query.

● Using the WillUpdateRows event to trap update operations and substitute appropriate stored procedure calls to perform the actual changes.

In summary, there are not very many situations where cursors are an optimal or viable way to access your data — especially on large production databases. However, there are situations
where you need to have the ability to:

● Scroll forwards and backwards (browse) through a limited result set.

● Move to a specific row based on a saved value (a bookmark).

● Move to the 'nth' row of a result set in absolute or relative terms.

● Update limited result sets created against base tables using the RemoteData control.

There are even fewer situations that justify inclusion of a query that simply creates an unrestrained cursor against one or more base tables. For example, "SELECT * FROM Table" is an example
of an unrestrained query. Not only is this not a permissible option in protected systems, but it can cause serious concurrency problems as you attempt to scale your application to more than a
few users. Whenever you create a cursor, be sure to limit the scope to the fewest number of rows possible. In interactive systems (where there is a human operator), fetching more than a few
hundred rows is often counterproductive and leads to increasingly complex concurrency problems.

Contact Us | E-Mail this Page | MSDN Flash Newsletter

© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon98/html/vbconCreatingRDOCursors.asp [11/18/2002 12:09:32 AM]

You might also like