MSDN Visual Basic 6
MSDN Visual Basic 6
MSDN Visual Basic 6
Go
Advanced Search
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:
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.
Enterprise Development
Read about how to develop business-critical distributed applications using 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
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
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions)
MSDN Library GO
Advanced Search Visual Basic Concepts
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.
Programming Fundamentals
Explains how to install Visual Basic and get assistance while you work.
An introduction to the integrated development environment and the process of creating your first application.
An introduction to the objects that you can put together to create an application.
Managing Projects
Programming Fundamentals
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Installing 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.
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.
For More Information See the Readme file for detailed instructions on installing 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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
For More Information See the Readme file for detailed instructions on installing 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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing Visual Basic > Installing Visual Basic
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.
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.
For More Information For more details about requirements, see "System Requirements for Visual Basic" in "Visual Basic Specifications, Limitations, and File Formats."
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
For More Information For more details about requirements, see "System Requirements for Visual Basic" in "Visual Basic Specifications, Limitations, and File Formats."
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
Help content includes several features designed to make finding information easier.
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.
Click the See Also link under the topic title to view the titles of topics you can go to for more or related information.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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)
● Visual Basic keywords (statements, functions, properties, methods, events, and special objects)
● Error messages
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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)
● Visual Basic keywords (statements, functions, properties, methods, events, and special objects)
● Error messages
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.")
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.
Note Some code examples require you to draw controls on the form. For more information on drawing controls, see "Forms, Controls, and Menus."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.")
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.
Note Some code examples require you to draw controls on the form. For more information on drawing controls, see "Forms, Controls, and Menus."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
See Also
If you have a modem or other means of access, additional information about Visual Basic is available on the web.
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?
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
● 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?
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Introducing 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 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
Topics
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Developing an Application in Visual Basic
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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 An introduction to the various parts of the IDE.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
2. Select Programs, Visual Studio and then Microsoft Visual Basic 6.0.
–or–
Select Programs.
Use the Windows Explorer to find the Visual Basic executable file.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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–
Select Programs.
Use the Windows Explorer to find the Visual Basic executable file.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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."
Lists the forms and modules in your current project. A project is the collection of files you use to build an application.
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.
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."
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."
The Form Layout window (Figure 2.2) allows you to position the forms in your application using a small graphical representation of the screen.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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."
Lists the forms and modules in your current project. A project is the collection of files you use to build an application.
Properties Window
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."
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."
The Form Layout window (Figure 2.2) allows you to position the forms in your application using a small graphical representation of the screen.
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.
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
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.
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.
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.
2. Drag the window to the desired location by holding down the left mouse button.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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.
2. Drag the window to the desired location by holding down the left mouse button.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
● The Firstapp Sample Application Create your first "real" application by duplicating the Firstapp sample application.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
See Also
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.
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
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.
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.)
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.
To resize a control
1. Select the control you intend to resize by clicking it with the mouse.
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.
–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.
–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.
● 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.
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.
● 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.
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.
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.
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.
● 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.
You can choose to display all procedures in the same Code window, or display a single procedure at a time.
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.
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.
● 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.
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.)
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:
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."
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
Up One Level There are three main steps to creating an application in Visual Basic:
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.
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
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.
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.)
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.
To resize a control
1. Select the control you intend to resize by clicking it with the mouse.
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.
–or–
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.
–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.
● 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.
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.
● 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.
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.
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.
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.
● 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.
You can choose to display all procedures in the same Code window, or display a single procedure at a time.
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.
2. On the Editor tab in the Options dialog box, clear the check box to the left of Default to Full Module View.
Click the Procedure View button in the lower left corner of the Code Editor window.
● 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.
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.)
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:
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."
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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:
1. Select Components from the context menu for the toolbox. (You can right-click within the toolbox window to display the context menu.)
2. Find the MSFlexGrid (Microsoft Flex Grid 6.0) in the Controls list box and select the check box to its left.
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.
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.
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:
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:
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:
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:
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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 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:
1. Select Components from the context menu for the toolbox. (You can right-click within the toolbox window to display the context menu.)
2. Find the MSFlexGrid (Microsoft Flex Grid 6.0) in the Controls list box and select the check box to its left.
The icon for the MSFlexGrid control will appear in the toolbox.
Setting Properties
In the Properties window, set properties for the objects according to the following table. Use the default settings for all other properties.
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.
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:
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:
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:
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).
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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
Designing a Form
An introduction to the check box, option button, list box, combo box, and scroll bar controls.
Additional Controls
Understanding Focus
Menu Basics
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus
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.
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.
Sub Balloon_Puncture()
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus
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.
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus
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.
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.
● 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.
cmdClose.Value = True
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.
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).
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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
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.
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).
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
● Using Labels to Display Text The basics of using the label control.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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
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.
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
The following table lists the property settings for the objects in the application.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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 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.
The following table lists the property settings for the objects in the application.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
A user can select only one option button in the group when you draw option buttons 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.
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.
● Tabbing to the option button group and then using the arrow keys to select an option button within the group.
optChoice.Value = True
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 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.
The following table lists the property settings for the objects in the application.
Value True
Value True
● 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:
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
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.
A user can select only one option button in the group when you draw option buttons 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.
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.
● Tabbing to the option button group and then using the arrow keys to select an option button within the group.
optChoice.Value = True
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 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.
The following table lists the property settings for the objects in the application.
Value True
Value True
● 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:
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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"
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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."
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).
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."
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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."
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).
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."
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
The following table lists the property settings for the objects in the application.
Height 735
Width 495
● 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:
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
Height 735
Width 495
● 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:
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus
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."
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus
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
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 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).
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.
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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.
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).
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.
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus
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.
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus
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.
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.
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."
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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).
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.
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."
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Forms, Controls, and Menus
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
A discussion of some of the options that can be set on a project by project basis.
A discussion of additional tools for working with projects and extending Visual Basic.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing 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 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.
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."
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
●
One project file that keeps track of all the components (.vbp).
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.
●
Optionally, one file for each class module (.cls).
Adding Controls to a Project ● Optionally, one or more files containing ActiveX controls (.ocx).
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."
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects
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 (.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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
Up One Level The following sections describe the different types of files and objects that you can include in a project.
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
For More Information For more information on ActiveX documents, see "Creating ActiveX Components" in the Component Tools Guide.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects
See Also
Four commands on the File menu allow you to create, open, and save 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 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.
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.
For More Information To learn more about working with multiple projects, see "Creating ActiveX Components" in the Component Tools Guide.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
Up One Level Four commands on the File menu allow you to create, open, and save projects.
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects
See Also
Working with files within a project is similar to working with the projects themselves.
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.
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.
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
Up One Level Working with files within a project is similar to working with the projects themselves.
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.
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.
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.
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.
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.
4. Select the name of the text file you want to insert, and choose Open.
In general, you should not edit attributes manually, as doing so may put the module into an internally inconsistent state.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects
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."
You can add ActiveX controls and insertable objects to your project by adding them to the toolbox.
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.
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).
2. Clear the check box next to each control you want to remove.
Note You cannot remove any control from the toolbox if an instance of that control is used on any form in the project.
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.
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.
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."
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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).
2. Clear the check box next to each control you want to remove.
Note You cannot remove any control from the toolbox if an instance of that control is used on any form in the project.
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.
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.
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."
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects
See Also
You can make an executable file (.exe) from Visual Basic using the following procedure.
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:
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
Up One Level You can make an executable file (.exe) from Visual Basic using the following procedure.
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.
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
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:
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."
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Managing Projects
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.
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
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.
Depending upon your Load Behavior selections, Visual Basic connects the selected add-ins and disconnects the cleared add-ins.
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.
–or–
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
To install an add-in
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.
Depending upon your Load Behavior selections, Visual Basic connects the selected add-ins and disconnects the cleared add-ins.
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
–or–
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
Topics
An introduction to the various components or modules that make up a Visual Basic application.
An introduction to the features of the Code Editor, plus the rules and regulations for writing code.
Introduction to Procedures
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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).
Note Many events occur in conjunction with other events. For example, when the DblClick event occurs, the MouseDown, MouseUp, and Click events also occur.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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).
Note Many events occur in conjunction with other events. For example, when the DblClick event occurs, the MouseDown, MouseUp, and Click events also occur.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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:
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.
You use assignment statements to perform calculations and assign the result to a variable:
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:
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 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.
● 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.
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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).
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.
You use assignment statements to perform calculations and assign the result to a variable:
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:
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 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.
● 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.
● 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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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:
–or–
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.
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:
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.
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:
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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:
–or–
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.
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:
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.
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:
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
See Also
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:
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:
The third intX variable is declared in the form module. And again, a procedure named Test sets its value.
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.
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.
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.
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.
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
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:
The third intX variable is declared in the form module. And again, a procedure named Test sets its value.
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.
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.
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.
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.
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
To make all local variables in a procedure static, place the Static keyword at the beginning of a procedure heading. For example:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
To make all local variables in a procedure static, place the Static keyword at the beginning of a procedure heading. For example:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
You can place more than one constant declaration on a single line if you separate them with commas:
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:
Once you define constants, you can place them in your code to make it more readable. For example:
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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.
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.
You can place more than one constant declaration on a single line if you separate them with commas:
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:
Once you define constants, you can place them in your code to make it more readable. For example:
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.
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.
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
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.
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."
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
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).
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.
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:
● Writing to files
● Calling DLLs
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."
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:
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.
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.
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.
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.
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.
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.
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.
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:
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
For More Information See the Language Reference for a specific conversion function.
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:
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.
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 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.
Z = Null
You can use the IsNull function to test if a Variant variable contains Null:
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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."
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
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).
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.
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:
● Writing to files
● Calling DLLs
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."
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:
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.
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.
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.
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.
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.
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.
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
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.
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:
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.
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:
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.
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 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.
Z = Null
You can use the IsNull function to test if a Variant variable contains Null:
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
See Also
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:
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:
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.
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:
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("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."
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
67 67
13 67
Note Visual Basic stores strings internally as Unicode. For more information on Unicode, see "International Issues."
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:
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:
Similarly, you can compare a date/time value with a complete date/time literal:
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:
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:
For More Information For information about the various date/time functions, see "Date Function" in the Language Reference.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
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:
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.
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.
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")
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."
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
67 67
13 67
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:
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:
Similarly, you can compare a date/time value with a complete date/time literal:
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:
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:
For More Information For information about the various date/time functions, see "Date Function" in the Language Reference.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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:
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:
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.
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.
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:
You can extend this to more than two dimensions. For example:
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.
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:
For More Information For information about loops, see "Loop Structures" later in this chapter.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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.
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.
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:
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:
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.
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.
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:
You can extend this to more than two dimensions. For example:
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
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:
For More Information For information about loops, see "Loop Structures" later in this chapter.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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()
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.
For example, the dynamic array Matrix1 is created by first declaring it at the module level:
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.
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:
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:
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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()
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.
For example, the dynamic array Matrix1 is created by first declaring it at the module level:
Sub CalcValuesNow ()
.
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.
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:
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:
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Code Writing Mechanics
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.
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
● 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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Code Writing Mechanics
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.
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.
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
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.
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Code Writing Mechanics
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.
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.
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:
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."
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:
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.
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.
9 &O11 &H9
15 &O17 &HF
16 &O20 &H10
20 &O24 &H14
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.
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 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.
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:
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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:
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."
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:
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.
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.
9 &O11 &H9
15 &O17 &HF
16 &O20 &H10
20 &O24 &H14
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.
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 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.
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:
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
● 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:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Procedures
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.
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Procedures
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.
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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:
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Procedures
See Also
● 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.
● 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.
3. Select the module from the Classes list, and the procedure from the Members of list.
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.
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.
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.
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:
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.
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)
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."
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)
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
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:
Visual Basic responds by completing the template for the new procedure.
● 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.
3. Select the module from the Classes list, and the procedure from the Members of list.
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.
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.
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.
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:
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.
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)
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."
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)
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction 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.
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:
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.
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:
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
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.
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.
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:
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
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:
This is especially useful if your procedures have several optional arguments that you do not always need to specify.
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
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.
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:
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
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.
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.
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:
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
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:
This is especially useful if your procedures have several optional arguments that you do not always need to specify.
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Control Structures
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
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):
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...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:
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.
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:
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
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):
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.
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:
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.
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:
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.
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Control Structures
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:
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
Two other variations are analogous to the previous two, except that they loop as long as condition is False rather than True.
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:
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.
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.)
This code prints the names of all the available Screen fonts:
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:
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.
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
● For collections, element can only be a Variant variable, a generic Object variable, or an object listed in the Object Browser.
● You cannot use For Each...Next with an array of user-defined types because a Variant cannot contain a user-defined type.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
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
Two other variations are analogous to the previous two, except that they loop as long as condition is False rather than True.
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:
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.
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.)
This code prints the names of all the available Screen fonts:
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:
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.
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
● For collections, element can only be a Variant variable, a generic Object variable, or an object listed in the Object Browser.
● You cannot use For Each...Next with an array of user-defined types because a Variant cannot contain a user-defined type.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Introduction to Control Structures
See Also
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:
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.
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:
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:
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.
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:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
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.
For example, this procedure prints all the font names that are common to both the Printer and Screen:
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.
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:
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:
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.
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:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects
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.
Database Databases are objects, and contain other objects, like fields and indexes.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working 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 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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > 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.
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.
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.
object.property = expression
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:
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.
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.
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
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:
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:
If there is no return value, the arguments appear without parentheses. For example, the AddItem method doesn't return a value:
For More Information See the Language Reference for the syntax and arguments for all methods provided by Visual Basic.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
object.property = expression
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:
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.
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.
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
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:
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:
If there is no return value, the arguments appear without parentheses. For example, the AddItem method doesn't return a value:
For More Information See the Language Reference for the syntax and arguments for all methods provided by Visual Basic.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects
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.
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.
For example, the following code scrolls through the Controls collection and lists each member's name in a list box.
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
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–
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
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
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.
You can use the Container property to change an object's container within a form. The following controls can contain other controls:
● Frame control
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.
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
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
For example, the following code scrolls through the Controls collection and lists each member's name in a list box.
● Specify the name of the member. The following expressions are equivalent:
Controls("List1")
Controls!List1
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–
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
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
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.
You can use the Container property to change an object's container within a form. The following controls can contain other controls:
● Frame control
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.
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
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Programmer's Guide (All Editions) > Part 1: Visual Basic Basics > Programming Fundamentals > Working with Objects
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 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."
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:
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:
For example, you can declare an object variable that refers to a form in the application called frmMain:
You can also declare an object variable that can refer to any form in the application:
Similarly, you can declare an object variable that can refer to any text box in your application:
You can also declare an object variable that can refer to a control of any type:
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:
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:
You can shorten this code significantly if you use a control variable:
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:
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:
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."
Generic Object
Type Object referenced
Form Any form in the application (including MDI children and the MDI form).
MDIForm The MDI form in the application (if your application has one).
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.
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:
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.
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.
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.
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.
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."
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 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.
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:
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:
The Form1_Click event procedure calls the GetPicture procedure in Form2, and passes the empty picture box to it.
The GetPicture procedure in Form2 assigns the Picture property of the picture box on Form2 to the empty picture box on Form1.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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."
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:
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:
For example, you can declare an object variable that refers to a form in the application called frmMain:
You can also declare an object variable that can refer to any form in the application:
Similarly, you can declare an object variable that can refer to any text box in your application:
You can also declare an object variable that can refer to a control of any type:
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:
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:
You can shorten this code significantly if you use a control variable:
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:
Run the application, and click the form. The Text property of the text box will be changed to "Hello."
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."
Generic Object
Type Object referenced
Form Any form in the application (including MDI children and the MDI form).
MDIForm The MDI form in the application (if your application has one).
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.
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:
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.
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.
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.
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.
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
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."
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 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.
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:
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:
The Form1_Click event procedure calls the GetPicture procedure in Form2, and passes the empty picture box to it.
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 >
MSDN Library GO
Advanced Search Visual Basic Concepts
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.
This designer provides an extensive design-time interface that enables you to create and modify Data Environment objects.
This designer allows you to generate data reports from several different relational tables.
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.
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.
Discusses the changes needed to upgrade an existing RDO-based project to Microsoft's new data access technology.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)
MSDN Library GO
Advanced Search Visual Basic Concepts
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
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.
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.
● The DataList and DataCombo controls are the ADO/OLE DB equivalents of DBList and DBCombo controls.
● 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 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic
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.
● 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.
● 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.
● 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
● DBCombo Control
● DBList Control
● FlexGrid Control
● Image Control
● Label Control
● ListBox Control
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
● 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.
● 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.
● 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.
● CheckBox Control
● ComboBox Control
● DBCombo Control
● DBList Control
● FlexGrid Control
● Image Control
● Label Control
● ListBox Control
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using 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.
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 detailed information about ADO, see the Introduction to the "ADO Programmer's Guide."
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
For detailed information about ADO, see the Introduction to the "ADO Programmer's Guide."
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.
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
For More Information For more background on OLE DB see Microsoft OLE DB Overview.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic
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.
For More Information For more background on OLE DB see Microsoft OLE DB Overview.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic
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.
● Data Environment
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.
For details about hierarchical cursors, see Hierarchical Cursors and Data Shaping. For details about the DataEnvironment, see About the Data Environment Designer.
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
●
Data-Aware Class Modules
● Data Environment
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.
For details about hierarchical cursors, see Hierarchical Cursors and Data Shaping. For details about the DataEnvironment, see About the Data Environment Designer.
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using 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.
Exceptions
The only data sources that cannot be bound in this manner are the intrinsic Data control and the RemoteData Control.
For More Information For more information about new data-bound controls, see Forms and Data-Aware Controls.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
Exceptions
The only data sources that cannot be bound in this manner are the intrinsic Data control and the RemoteData Control.
For More Information For more information about new data-bound controls, see Forms and Data-Aware Controls.
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using 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.
Option Explicit
While code on the client machine that calls the function would be:
Option Explicit
Private myrec As udtMyType
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.
While code on the client machine that calls the function would be:
Option Explicit
Private SomeServer As Object
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
While code on the client machine that calls the function would be:
Option Explicit
Private myrec As udtMyType
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.
While code on the client machine that calls the function would be:
Option Explicit
Private SomeServer As Object
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Accessing Data Using Visual Basic
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)
MSDN Library GO
Advanced Search Visual Basic Concepts
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.
For information on controls related to data access, see the Programmer's Guide:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic
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.
● Database Designer
● Query Designer
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
Database Designer
Wizards Related to Data Access
●
● Query Designer
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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.
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.
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.
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.
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic > Format Objects
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.
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.
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.
9. Run the project and experiment with the ADO Data control.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
9. Run the project and experiment with the ADO Data control.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic
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 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.
1. In Data View, right-click the Stored Procedures folder or any stored procedure in that folder.
3. Replace StoredProcedure in the first line with the name of the procedure. For example, you might use "MyProcedure" as the name:
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.
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.
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.
2. Right-click the name of the stored procedure that you want to copy. Choose Design from the shortcut menu.
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.
7. Right-click the SQL Editor. Choose Paste from the shortcut menu to create your new stored procedure.
You can edit the SQL statements in the new stored procedure.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
●
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.
1. In Data View, right-click the Stored Procedures folder or any stored procedure in that folder.
3. Replace StoredProcedure in the first line with the name of the procedure. For example, you might use "MyProcedure" as the name:
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.
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.
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.
2. Right-click the name of the stored procedure that you want to copy. Choose Design from the shortcut menu.
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.
7. Right-click the SQL Editor. Choose Paste from the shortcut menu to create your new stored procedure.
You can edit the SQL statements in the new stored procedure.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic
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.
● 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 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:
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:
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
3. Right-click the name of the trigger that you want to open and click Design on the shortcut menu.
-or-
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
3. Right-click the trigger that you want to delete and choose Delete from the shortcut menu.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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 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 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:
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:
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
3. Right-click the name of the trigger that you want to open and click Design on the shortcut menu.
-or-
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
3. Right-click the trigger that you want to delete and choose Delete from the shortcut menu.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic
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.
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.
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.
● By right-clicking a stored procedure in the Data View window and choosing the Debug command
Once you have started the debugger, it establishes the ODBC connection and displays the Enter Unassigned Parameters dialog box, as shown.
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:
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
● Step
● Run to cursor
● Stop debugging
● Restart
The Options menu lets you customize the appearance of the T-SQL debugger by changing the fonts and colors used for display.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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 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.
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.
● By right-clicking a stored procedure in the Data View window and choosing the Debug command
Once you have started the debugger, it establishes the ODBC connection and displays the Enter Unassigned Parameters dialog box, as shown.
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:
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
● Step
● Run to cursor
● Stop debugging
● Restart
The Options menu lets you customize the appearance of the T-SQL debugger by changing the fonts and colors used for display.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
5. Write Visual Basic code that creates an instance of the new UserConnection class and calls any of its queries as methods.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic > The UserConnection Designer
See Also
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.
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.
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
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
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.
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 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
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.
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.
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
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
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.
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 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic > The UserConnection Designer
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.
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:
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.
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:
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 properties
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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:
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.
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:
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 properties
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Data Access Tools in Visual Basic
See Also
Three Visual Basic wizards can assist you in your data access programming:
● MS FlexGrid Wizard
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
Up One Level Three Visual Basic wizards can assist you in your data access programming:
● MS FlexGrid Wizard
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Reference >
MSDN Library GO
Advanced Search Visual Basic: 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
●
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
● Control Selection
● Finished!
In addition to the previous steps, data forms that contain ADO Data controls, also have a Connect Information step.
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Reference >
MSDN Library GO
Advanced Search Visual Basic: 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.
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.
● Create user controls that display and allow you to interact with lookup relationships.
Wizard Manager ● Have meaningful text descriptions instead of cryptic lookup values.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Library GO
Advanced Search Visual Basic: FlexGrid Wizard
See Also
Allows you to select the type of MSHFlexGrid form you want to create.
Options
Grid Type
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)
MSDN Library GO
Advanced Search Visual Basic Concepts
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 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.
● Drag fields within a Command object from the Data Environment designer onto a Visual Basic form or the Data Report designer.
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.
● 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.
● 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.
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.
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
● Connection Objects
● Command Objects
● Field Mapping
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer
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.
2. From the References dialog box, select Data Environment 1.0, and then click OK.
1. From the New tab of the New Project dialog box, choose Standard EXE project, and then click Open.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer
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.
The Add Connection function is available at all times and is independent of the existence of other objects.
-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.
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.
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.
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.
The miscellaneous connection information consists of advanced options that change how the database is accessed.
● 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.
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).
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
-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.
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.
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.
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.
The miscellaneous connection information consists of advanced options that change how the database is accessed.
● 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.
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).
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer
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).
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.
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.
-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.
1. Right-click the Connection object and choose Properties to access the Command Properties dialog box.
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–
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.
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.
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.
Scale Specify the maximum number of digits to the right of the decimal point.
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.
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.
You can create multiple Command objects in your Data Environment designer from stored procedures using the Insert Stored Procedures dialog box.
-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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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.
-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.
1. Right-click the Connection object and choose Properties to access the Command Properties dialog box.
Item Purpose
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.
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.
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.
Scale Specify the maximum number of digits to the right of the decimal point.
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.
You can create multiple Command objects in your Data Environment designer from stored procedures using the Insert Stored Procedures dialog box.
-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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies
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.
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.
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.
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.
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.
-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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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.
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.
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.
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.
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.
-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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies
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.
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."
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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."
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies
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.
Count Returns the count of the number of records of the selected field.
Sum Returns the sum of all the values of the selected field.
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.
Note To delete an aggregate from the Aggregates box, select the aggregate to delete, and then click Remove.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
Count Returns the count of the number of records of the selected field.
Sum Returns the sum of all the values of the selected field.
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.
Note To delete an aggregate from the Aggregates box, select the aggregate to delete, and then click Remove.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer > Command Hierarchies
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer
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.
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.
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.
1. Select a Command object and click Options on the Data Environment designer toolbar.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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.
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer
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.
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.
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.
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.
1. Right-click on the DataEnvironment object. The DataEnvironment object is the top-most object in your Data Environment outline view.
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.
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.
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.
● 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.
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.
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.
The Refresh function differs in function between Connection and Command objects.
Note Refreshing a Connection object does not automatically refresh its associated Command objects.
Caution Refreshing a Command object removes user-defined data, including parameter and field mapping information. Once removed, it cannot be retrieved.
● 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).
You can change the display of warning and confirmation dialog boxes using the Options dialog box.
-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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
1. Right-click on the DataEnvironment object. The DataEnvironment object is the top-most object in your Data Environment outline view.
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.
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.
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.
● 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.
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.
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.
The Refresh function differs in function between Connection and Command objects.
Note Refreshing a Connection object does not automatically refresh its associated Command objects.
Caution Refreshing a Command object removes user-defined data, including parameter and field mapping information. Once removed, it cannot be retrieved.
● 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).
You can change the display of warning and confirmation dialog boxes using the Options dialog box.
-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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer
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.
-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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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-
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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.
2. Select an option from the menu: Data Grid, multiple-bound controls, or any control associated with the multiple setting.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
2. Select an option from the menu: Data Grid, multiple-bound controls, or any control associated with the multiple setting.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
You can also programmatically create instances of your Data Environment by declaring a variable within a procedure using the DIM statement. For example:
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.
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.
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.
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.
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
● 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.
You can also programmatically create instances of your Data Environment by declaring a variable within a procedure using the DIM statement. For example:
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.
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.
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.
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.
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer
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 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.
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.
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.
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.
6. On the General tab, click SQL Statement and type the following parameterized query:
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."
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"
11. Run the project and click the button. Change the text in Text1 to run another query.
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.
Although it's possible to insert a stored procedure into a hierarchy as a child command, there are two conditions that must be met:
● After inserting the stored procedure into a hierarchy, you must set the Required check box for any parameters to False.
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.
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.
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:
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.
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.
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.
The differences may account for some confusion when trying to program the DataEnvironment object.
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:
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
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:
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
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.
6. On the General tab, click SQL Statement and type the following parameterized query:
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."
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
11. Run the project and click the button. Change the text in Text1 to run another query.
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.
Although it's possible to insert a stored procedure into a hierarchy as a child command, there are two conditions that must be met:
● After inserting the stored procedure into a hierarchy, you must set the Required check box for any parameters to False.
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.
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.
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:
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.
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.
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.
The differences may account for some confusion when trying to program the DataEnvironment object.
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:
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
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:
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:
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About the Data Environment Designer
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.
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.
By using the Extensibility Object Model you can use your Data Environment in an add-in. The add-in can be:
● An alternative interface (other than the Data Environment) to create and modify DataEnvironment objects.
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
By using the Extensibility Object Model you can use your Data Environment in an add-in. The add-in can be:
● An alternative interface (other than the Data Environment) to create and modify DataEnvironment objects.
● 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.
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > About 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.
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.
To add an aggregate to the Customer Command object to obtain the SUM of the order amounts for all orders per customer
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.
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.
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
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.
The following scenario is provided so you can view the results of the previous scenarios. See the Hierarchical FlexGrid Control for more information.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
To add an aggregate to the Customer Command object to obtain the SUM of the order amounts for all orders per customer
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.
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.
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
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.
The following scenario is provided so you can view the results of the previous scenarios. See the Hierarchical FlexGrid Control for more information.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)
MSDN Library GO
Advanced Search Visual Basic Concepts
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
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.
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer
See Also
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."
● 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.
When a new Data Report designer is added to a project, the following controls are automatically placed in the Toolbox tab named DataReport:
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
Up One Level The Data Report designer consists of the following objects:
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."
● 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.
When a new Data Report designer is added to a project, the following controls are automatically placed in the Toolbox tab named DataReport:
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
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
Connection Northwind
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
Connection Northwind
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.
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:
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.
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
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.
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.
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.
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.
1. On the Project Explorer window, double-click the frmShowReport icon to display the Form designer.
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.
4. Set the properties of the Command1 control according to the table below:
Property Setting
Name cmdShow
You can also display the data report with no code at all.
Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
1. On the Data Environment designer, right-click the Orders Command object. Then click Add Child Command.
Property Setting
Connection Northwind
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
4. Right-click the OrderDetails Command object, and click Add Child Command. Set the properties of the connection as shown below:
Property Setting
Connection Northwind
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.
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.
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.
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.
Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
1. On the Data Environment designer, right-click the Orders Command object. Then click Add Child Command.
Property Setting
Connection Northwind
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
Connection Northwind
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.
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.
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.
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.
Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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.
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.
Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
2. Adding three text box controls to the data report: Quantity, UnitPrice, and (for the calculated field) Total.
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.
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.
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.
Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.)
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.
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.
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.
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.
1. Draw a new Function control in the Customers_Footer section. Align the new control with the Function control created above.
4. The Data Report designer should now resemble the figure below:
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.
1. Right-click the Data Report designer and click Show Report Header/Footer.
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.
Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.)
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.
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.
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.
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.
1. Draw a new Function control in the Customers_Footer section. Align the new control with the Function control created above.
4. The Data Report designer should now resemble the figure below:
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.
1. Right-click the Data Report designer and click Show Report Header/Footer.
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.
Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
1. In the Data Environment designer, right click the Customers Command object. Click Properties to show the Customers Properties dialog box.
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:
Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
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.
1. In the Data Environment designer, right click the Customers Command object. Click Properties to show the Customers Properties dialog box.
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:
Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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:
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.
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.
1. On the Data Environment designer, open the Detail Fields in Customers folder, and right-click Orders, then click Properties.
6. In the Aggregate combo box, select OrderDetails (it should be selected by default).
Now that you have created the aggregate field, you can place it on the Data Report designer.
1. From the Data Environment designer, drag the ProductCount aggregate field onto the group section named Orders_Header.
3. Reposition and resize the TextBox control and the Label control so the designer resembles the figure below:
Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
1. On the Data Environment designer, open the Detail Fields in Customers folder, and right-click Orders, then click Properties.
6. In the Aggregate combo box, select OrderDetails (it should be selected by default).
1. From the Data Environment designer, drag the ProductCount aggregate field onto the group section named Orders_Header.
3. Reposition and resize the TextBox control and the Label control so the designer resembles the figure below:
Step by Step
This topic is part of a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
2. On the Properties window, click ForcePageBreak, then click the arrow that appears at the right of the box.
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.)
2. On the Properties window, click ForcePageBreak, then click the arrow that appears at the right of the box.
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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
Report Title %i
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.
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.
9. Position the new control in the far right corner of the designer.
Step by Step
This topic is the last in a series that walks you through creating a sample data report.
To See
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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 Date, Time, Page Number, and Title to the Data Report
Function Code
Report Title %i
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.
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.
9. Position the new control in the far right corner of the designer.
Step by Step
This topic is the last in a series that walks you through creating a sample data report.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer
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.
By default, the ExportFormats collection contains four members. The four members and their associated file filters are shown in the chart below:
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:
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
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.
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:
rptTagTitle <!--MSDBRPT_Template_Title--> Represents the title of the report, as found in the Title property.
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:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
By default, the ExportFormats collection contains four members. The four members and their associated file filters are shown in the chart below:
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:
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
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.
rptTagTitle <!--MSDBRPT_Template_Title--> Represents the title of the report, as found in the Title property.
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:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer
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.
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.
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.
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.
DataReport1.PrintReport False
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
DataReport1.PrintReport False
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft Data Report Designer
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.
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.
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.
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.
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.
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:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
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.
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.
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.
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.
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:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Writing Reports with the Microsoft 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.
2. Set the DataSource property of the Data Report designer to the Data Environment designer.
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.
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.
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:
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.
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.
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.
For More Information Details about creating aggregate field can be found in "Creating Aggregates" in "Using the Data Environment Designer."
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
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:
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.
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.
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.
For More Information Details about creating aggregate field can be found in "Creating Aggregates" in "Using the Data Environment Designer."
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)
MSDN Library GO
Advanced Search Visual Basic Concepts
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database
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.
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.
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.
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
Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
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.
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
Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database
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.
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 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
Connection Connection1
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
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
Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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 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
Connection Connection1
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.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
Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database
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.
1. Drag a Command object from the Data Environment designer to a blank form.
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.
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
Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
1. Drag a Command object from the Data Environment designer to a blank form.
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.
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
Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database
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.
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.
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
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:
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.
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
Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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
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
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:
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.
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
Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database
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.
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.
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
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:
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
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:
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
Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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
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:
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
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:
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
Start from the beginning Interacting with Data in a Microsoft Jet/Microsoft Access Database
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in a Microsoft Jet/Microsoft Access Database
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.
3. Drag the Command object from the Data Environment designer to the Data Report 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.
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.
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.
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
3. Drag the Command object from the Data Environment designer to the Data Report 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.
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.
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.
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)
MSDN Library GO
Advanced Search Visual Basic Concepts
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:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server Data
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.
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.
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.
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 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:
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
Start from the beginning Creating a DHTML Application that Interacts with SQL Server Data
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
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.
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.
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.
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 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:
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
Start from the beginning Creating a DHTML Application that Interacts with SQL Server Data
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server Data
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.
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.
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 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
Connection Connection1
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."
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:
End Function
For More Information For more information on using ADO, see ADO, DAO and RDO in Visual Basic.
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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 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..
Property Setting
Connection Connection1
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."
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:
End Function
For More Information For more information on using ADO, see ADO, DAO and RDO in Visual Basic.
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server 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.
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.
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.
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.
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:
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:
End Sub
For More Information For more information see BindingCollection object in the Language Reference.
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.
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
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.
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:
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:
End Sub
For More Information For more information see BindingCollection object in the Language Reference.
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.
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Create a DHTML Application that Interacts with SQL Server Data
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.
5. Add code to run the stored procedure and display the results.
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.
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:
For More Information For more information on using the Data View window to create a stored procedure, see Stored Procedures in the SQL Editor.
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
Connection Connection1
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:
' 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:
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:
' 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>" & _
End Sub
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
5. Add code to run the stored procedure and display the results.
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.
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:
For More Information For more information on using the Data View window to create a stored procedure, see Stored Procedures in the SQL Editor.
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
Connection Connection1
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:
' 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:
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:
' 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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)
MSDN Library GO
Advanced Search Visual Basic Concepts
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 class and form to write records back to the delimited text file
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File
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
2. Add code to read data from the text file into an ADO recordset.
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.
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:
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:
With rsCustomers
' Set CustomerID as the primary key.
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
fld.Value = strField
Next
.Update
.MoveFirst
End With
Loop
Close
End Sub
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
2. Add code to read data from the text file into an ADO recordset.
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.
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:
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:
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
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
fld.Value = strField
Next
.Update
.MoveFirst
End With
Loop
Close
End Sub
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File
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
2. Add code to bind the text box controls to the data source.
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.
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:
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:
End Sub
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
2. Add code to bind the text box controls to the data source.
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.
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:
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:
End Sub
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File
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.
1. Create command buttons for allowing data entry, adding new customer records, and returning to viewing data.
3. Add code to enable saving the data you enter as a new record.
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.
● 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.
For example, to enable the DataEntry command button on the customer address form, add the following code to the DataEntry_Click event procedure:
' Show the command buttons used for entering new data.
Me.AddCustomer.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:
End With
End Sub
For example, to enable the ViewData command button on the customer address form, add the following code to the ViewData_Click event procedure:
' 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
Start from the beginning Interacting with Data in an ASCII Text File
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
3. Add code to enable saving the data you enter as a new record.
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.
● 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.
For example, to enable the DataEntry command button on the customer address form, add the following code to the DataEntry_Click event procedure:
' 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:
End With
End Sub
For example, to enable the ViewData command button on the customer address form, add the following code to the ViewData_Click event procedure:
' 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.
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Interacting with Data in an ASCII Text File
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
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.
To create a public WriteToFile method, add the following code to the CustomerDataSource class:
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
To create a public WriteToFile method, add the following code to the CustomerDataSource class:
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)
MSDN Library GO
Advanced Search Visual Basic Concepts
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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".
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Converting from RDO to ADO
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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:
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.
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.
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:
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:
The following declarations initialize the variables used in this example. (Note the creation of a variant array to hold the resultset):
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
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.
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.
ADO
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:
The following declarations initialize the variables used in this example. (Note the creation of a variant array to hold the resultset):
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
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
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.
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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.
Cmd.Parameters(0).Value = QueryParam.Text
Set rs = Cmd.Execute()
ADOGrid1.ShowData rs
rs.Close
End Sub
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
Performing an Action Query 2. Perform the query again with new parameters.
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.
Cmd.Parameters(0).Value = QueryParam.Text
Set rs = Cmd.Execute()
ADOGrid1.ShowData rs
rs.Close
End Sub
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
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.
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.
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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).
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
ADO
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)
MSDN Library GO
Advanced Search Visual Basic Concepts
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.
Outlines issues relevant to opening a connection to an ODBC data source with the Jet engine.
Overviews issues relevant to performing queries on remote databases with the Jet engine.
Briefly describes issues relevant to sharing a database among users and applications.
Outlines issues involved in handling errors during DAO remote database access.
Briefly describes the ODBCDirect option, which maps DAO to Remote Data Objects.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases
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.
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.”
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.”
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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:
● Submitting an action query that changes the default database once the connection is open.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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:
● Submitting an action query that changes the default database once the connection is open.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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.
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".
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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".
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
● 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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only) > Using Data Access Objects with Remote Databases
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
MSDN Home > MSDN Library > Visual Basic 6.0 > Data Access Guide (Pro, Enterprise only)
MSDN Library GO
Advanced Search Visual Basic Concepts
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
Discusses what features are provided by RDO and how they map to more familiar DAO features.
An overview of the rdoEnvironment object and how to apply its properties to data access issues.
How to deal with the data and parameters returned from queries.
How to retrieve data through bound controls using the RemoteData control.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
● 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.
● 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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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:
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)
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
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)
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
rdoEngine DBEngine
rdoError Error
rdoEnvironment Workspace
rdoConnection Database
rdoTable TableDef
rdoResultset Recordset
Keyset-type Dynaset-type
Dynamic-type (none)
(cursorless) (none)
rdoColumn Field
rdoQuery QueryDef
rdoParameter Parameter
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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 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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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 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", _
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
rdoDefaultCursorDriver Cursor library (ODBC, client batch, server-side, or none) rdUseIfNeeded (server-side cursors)
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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)
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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".
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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".
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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.
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.
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.
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
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.
Note It is no longer always necessary to reference the rdoEnvironment object because rdoConnection objects can be created as stand-alone objects.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
● 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.
Note It is no longer always necessary to reference the rdoEnvironment object because rdoConnection objects can be created as stand-alone objects.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
●
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.
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.
● Execute a query that returns one or more result sets using the OpenResultset method.
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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:
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.
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.
WSID= The workstation ID. Typically, this is the network name of the computer on which the application resides (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.
Note that the connect string does not include arguments to set the following options:
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.
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=;"
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:
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
WSID= The workstation ID. Typically, this is the network name of the computer on which the application resides (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.
Note that the connect string does not include arguments to set the following options:
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.
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=;"
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:
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
● Connect property of the rdoConnection object used with the EstablishConnection method.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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
●
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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$)
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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 an rdoConnection Object LoginTimeout 15 How many seconds to wait before abandoning the connection attempt.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
● 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
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
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.
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:
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
See Also
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
Up One Level Once the rdoConnection object is created, you can use it to:
● 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.
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
See Also
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
See Also
Up One Level You might be unable to establish a connection for a variety of reasons, including:
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.
For More Information See the Language Reference for details on the structure and properties of the rdoError object.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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?
● 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.
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
● 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.
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".
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
● 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.
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".
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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.
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.
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:
● 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:
– or –
– or –
● 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:
– or –
– or –
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."
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.
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.
The following table summarizes the options available when using each of the three syntax styles:
Syntax Options
Can pass native SQL that does not reference a stored procedure 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.
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.
Next, create an rdoQuery object to manage the query and its parameters.
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).
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:
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
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:
● 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:
– or –
– or –
● 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:
– or –
– or –
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."
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.
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.
The following table summarizes the options available when using each of the three syntax styles:
Syntax Options
Can pass native SQL that does not reference a stored procedure 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.
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.
Next, create an rdoQuery object to manage the query and its parameters.
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).
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:
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."
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
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:
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.
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.
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:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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:
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.
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.
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:
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
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
See Also
Using the same technique used with parameter queries in SELECT statements, you can also capture the output parameters from a procedure.
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.
When the query has completed processing, retrieve the output parameter values from the rdoParameters collection.
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.
Ps(0).Direction = rdParamReturnValue
Ps(3).Direction = rdParamOutput
Ps(4).Direction = rdParamOutput
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
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.
When the query has completed processing, retrieve the output parameter values from the rdoParameters collection.
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.
Ps(0).Direction = rdParamReturnValue
Ps(3).Direction = rdParamOutput
Ps(4).Direction = rdParamOutput
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility
MSDN Home | MSDN Library | Downloads | Code Center | Site Map | MSDN Worldwide |
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
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.
● 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:
● 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.
© 2002 Microsoft Corporation. All rights reserved. Terms of Use Privacy Statement Accessibility