
- •Using Your Sybex Electronic Book
- •Acknowledgments
- •Contents at a Glance
- •Introduction
- •Who Should Read This Book?
- •How About the Advanced Topics?
- •The Structure of the Book
- •How to Reach the Author
- •The Integrated Development Environment
- •The Start Page
- •Project Types
- •Your First VB Application
- •Making the Application More Robust
- •Making the Application More User-Friendly
- •The IDE Components
- •The IDE Menu
- •The Toolbox Window
- •The Solution Explorer
- •The Properties Window
- •The Output Window
- •The Command Window
- •The Task List Window
- •Environment Options
- •A Few Common Properties
- •A Few Common Events
- •A Few Common Methods
- •Building a Console Application
- •Summary
- •Building a Loan Calculator
- •How the Loan Application Works
- •Designing the User Interface
- •Programming the Loan Application
- •Validating the Data
- •Building a Math Calculator
- •Designing the User Interface
- •Programming the MathCalculator App
- •Adding More Features
- •Exception Handling
- •Taking the LoanCalculator to the Web
- •Working with Multiple Forms
- •Working with Multiple Projects
- •Executable Files
- •Distributing an Application
- •VB.NET at Work: Creating a Windows Installer
- •Finishing the Windows Installer
- •Running the Windows Installer
- •Verifying the Installation
- •Summary
- •Variables
- •Declaring Variables
- •Types of Variables
- •Converting Variable Types
- •User-Defined Data Types
- •Examining Variable Types
- •Why Declare Variables?
- •A Variable’s Scope
- •The Lifetime of a Variable
- •Constants
- •Arrays
- •Declaring Arrays
- •Initializing Arrays
- •Array Limits
- •Multidimensional Arrays
- •Dynamic Arrays
- •Arrays of Arrays
- •Variables as Objects
- •So, What’s an Object?
- •Formatting Numbers
- •Formatting Dates
- •Flow-Control Statements
- •Test Structures
- •Loop Structures
- •Nested Control Structures
- •The Exit Statement
- •Summary
- •Modular Coding
- •Subroutines
- •Functions
- •Arguments
- •Argument-Passing Mechanisms
- •Event-Handler Arguments
- •Passing an Unknown Number of Arguments
- •Named Arguments
- •More Types of Function Return Values
- •Overloading Functions
- •Summary
- •The Appearance of Forms
- •Properties of the Form Control
- •Placing Controls on Forms
- •Setting the TabOrder
- •VB.NET at Work: The Contacts Project
- •Anchoring and Docking
- •Loading and Showing Forms
- •The Startup Form
- •Controlling One Form from within Another
- •Forms vs. Dialog Boxes
- •VB.NET at Work: The MultipleForms Project
- •Designing Menus
- •The Menu Editor
- •Manipulating Menus at Runtime
- •Building Dynamic Forms at Runtime
- •The Form.Controls Collection
- •VB.NET at Work: The DynamicForm Project
- •Creating Event Handlers at Runtime
- •Summary
- •The TextBox Control
- •Basic Properties
- •Text-Manipulation Properties
- •Text-Selection Properties
- •Text-Selection Methods
- •Undoing Edits
- •VB.NET at Work: The TextPad Project
- •Capturing Keystrokes
- •The ListBox, CheckedListBox, and ComboBox Controls
- •Basic Properties
- •The Items Collection
- •VB.NET at Work: The ListDemo Project
- •Searching
- •The ComboBox Control
- •The ScrollBar and TrackBar Controls
- •The ScrollBar Control
- •The TrackBar Control
- •Summary
- •The Common Dialog Controls
- •Using the Common Dialog Controls
- •The Color Dialog Box
- •The Font Dialog Box
- •The Open and Save As Dialog Boxes
- •The Print Dialog Box
- •The RichTextBox Control
- •The RTF Language
- •Methods
- •Advanced Editing Features
- •Cutting and Pasting
- •Searching in a RichTextBox Control
- •Formatting URLs
- •VB.NET at Work: The RTFPad Project
- •Summary
- •What Is a Class?
- •Building the Minimal Class
- •Adding Code to the Minimal Class
- •Property Procedures
- •Customizing Default Members
- •Custom Enumerations
- •Using the SimpleClass in Other Projects
- •Firing Events
- •Shared Properties
- •Parsing a Filename String
- •Reusing the StringTools Class
- •Encapsulation and Abstraction
- •Inheritance
- •Inheriting Existing Classes
- •Polymorphism
- •The Shape Class
- •Object Constructors and Destructors
- •Instance and Shared Methods
- •Who Can Inherit What?
- •Parent Class Keywords
- •Derived Class Keyword
- •Parent Class Member Keywords
- •Derived Class Member Keyword
- •MyBase and MyClass
- •Summary
- •On Designing Windows Controls
- •Enhancing Existing Controls
- •Building the FocusedTextBox Control
- •Building Compound Controls
- •VB.NET at Work: The ColorEdit Control
- •VB.NET at Work: The Label3D Control
- •Raising Events
- •Using the Custom Control in Other Projects
- •VB.NET at Work: The Alarm Control
- •Designing Irregularly Shaped Controls
- •Designing Owner-Drawn Menus
- •Designing Owner-Drawn ListBox Controls
- •Using ActiveX Controls
- •Summary
- •Programming Word
- •Objects That Represent Text
- •The Documents Collection and the Document Object
- •Spell-Checking Documents
- •Programming Excel
- •The Worksheets Collection and the Worksheet Object
- •The Range Object
- •Using Excel as a Math Parser
- •Programming Outlook
- •Retrieving Information
- •Recursive Scanning of the Contacts Folder
- •Summary
- •Advanced Array Topics
- •Sorting Arrays
- •Searching Arrays
- •Other Array Operations
- •Array Limitations
- •The ArrayList Collection
- •Creating an ArrayList
- •Adding and Removing Items
- •The HashTable Collection
- •VB.NET at Work: The WordFrequencies Project
- •The SortedList Class
- •The IEnumerator and IComparer Interfaces
- •Enumerating Collections
- •Custom Sorting
- •Custom Sorting of a SortedList
- •The Serialization Class
- •Serializing Individual Objects
- •Serializing a Collection
- •Deserializing Objects
- •Summary
- •Handling Strings and Characters
- •The Char Class
- •The String Class
- •The StringBuilder Class
- •VB.NET at Work: The StringReversal Project
- •VB.NET at Work: The CountWords Project
- •Handling Dates
- •The DateTime Class
- •The TimeSpan Class
- •VB.NET at Work: Timing Operations
- •Summary
- •Accessing Folders and Files
- •The Directory Class
- •The File Class
- •The DirectoryInfo Class
- •The FileInfo Class
- •The Path Class
- •VB.NET at Work: The CustomExplorer Project
- •Accessing Files
- •The FileStream Object
- •The StreamWriter Object
- •The StreamReader Object
- •Sending Data to a File
- •The BinaryWriter Object
- •The BinaryReader Object
- •VB.NET at Work: The RecordSave Project
- •The FileSystemWatcher Component
- •Properties
- •Events
- •VB.NET at Work: The FileSystemWatcher Project
- •Summary
- •Displaying Images
- •The Image Object
- •Exchanging Images through the Clipboard
- •Drawing with GDI+
- •The Basic Drawing Objects
- •Drawing Shapes
- •Drawing Methods
- •Gradients
- •Coordinate Transformations
- •Specifying Transformations
- •VB.NET at Work: Plotting Functions
- •Bitmaps
- •Specifying Colors
- •Defining Colors
- •Processing Bitmaps
- •Summary
- •The Printing Objects
- •PrintDocument
- •PrintDialog
- •PageSetupDialog
- •PrintPreviewDialog
- •PrintPreviewControl
- •Printer and Page Properties
- •Page Geometry
- •Printing Examples
- •Printing Tabular Data
- •Printing Plain Text
- •Printing Bitmaps
- •Using the PrintPreviewControl
- •Summary
- •Examining the Advanced Controls
- •How Tree Structures Work
- •The ImageList Control
- •The TreeView Control
- •Adding New Items at Design Time
- •Adding New Items at Runtime
- •Assigning Images to Nodes
- •Scanning the TreeView Control
- •The ListView Control
- •The Columns Collection
- •The ListItem Object
- •The Items Collection
- •The SubItems Collection
- •Summary
- •Types of Errors
- •Design-Time Errors
- •Runtime Errors
- •Logic Errors
- •Exceptions and Structured Exception Handling
- •Studying an Exception
- •Getting a Handle on this Exception
- •Finally (!)
- •Customizing Exception Handling
- •Throwing Your Own Exceptions
- •Debugging
- •Breakpoints
- •Stepping Through
- •The Local and Watch Windows
- •Summary
- •Basic Concepts
- •Recursion in Real Life
- •A Simple Example
- •Recursion by Mistake
- •Scanning Folders Recursively
- •Describing a Recursive Procedure
- •Translating the Description to Code
- •The Stack Mechanism
- •Stack Defined
- •Recursive Programming and the Stack
- •Passing Arguments through the Stack
- •Special Issues in Recursive Programming
- •Knowing When to Use Recursive Programming
- •Summary
- •MDI Applications: The Basics
- •Building an MDI Application
- •Built-In Capabilities of MDI Applications
- •Accessing Child Forms
- •Ending an MDI Application
- •A Scrollable PictureBox
- •Summary
- •What Is a Database?
- •Relational Databases
- •Exploring the Northwind Database
- •Exploring the Pubs Database
- •Understanding Relations
- •The Server Explorer
- •Working with Tables
- •Relationships, Indices, and Constraints
- •Structured Query Language
- •Executing SQL Statements
- •Selection Queries
- •Calculated Fields
- •SQL Joins
- •Action Queries
- •The Query Builder
- •The Query Builder Interface
- •SQL at Work: Calculating Sums
- •SQL at Work: Counting Rows
- •Limiting the Selection
- •Parameterized Queries
- •Calculated Columns
- •Specifying Left, Right, and Inner Joins
- •Stored Procedures
- •Summary
- •How About XML?
- •Creating a DataSet
- •The DataGrid Control
- •Data Binding
- •VB.NET at Work: The ViewEditCustomers Project
- •Binding Complex Controls
- •Programming the DataAdapter Object
- •The Command Objects
- •The Command and DataReader Objects
- •VB.NET at Work: The DataReader Project
- •VB.NET at Work: The StoredProcedure Project
- •Summary
- •The Structure of a DataSet
- •Navigating the Tables of a DataSet
- •Updating DataSets
- •The DataForm Wizard
- •Handling Identity Fields
- •Transactions
- •Performing Update Operations
- •Updating Tables Manually
- •Building and Using Custom DataSets
- •Summary
- •An HTML Primer
- •HTML Code Elements
- •Server-Client Interaction
- •The Structure of HTML Documents
- •URLs and Hyperlinks
- •The Basic HTML Tags
- •Inserting Graphics
- •Tables
- •Forms and Controls
- •Processing Requests on the Server
- •Building a Web Application
- •Interacting with a Web Application
- •Maintaining State
- •The Web Controls
- •The ASP.NET Objects
- •The Page Object
- •The Response Object
- •The Request Object
- •The Server Object
- •Using Cookies
- •Handling Multiple Forms in Web Applications
- •Summary
- •The Data-Bound Web Controls
- •Simple Data Binding
- •Binding to DataSets
- •Is It a Grid, or a Table?
- •Getting Orders on the Web
- •The Forms of the ProductSearch Application
- •Paging Large DataSets
- •Customizing the Appearance of the DataGrid Control
- •Programming the Select Button
- •Summary
- •How to Serve the Web
- •Building a Web Service
- •Consuming the Web Service
- •Maintaining State in Web Services
- •A Data-Driven Web Service
- •Consuming the Products Web Service in VB
- •Summary

WORKING WITH MULTIPLE FORMS 63
Figure 2.9
Editing the Web form’s HTML code
Click F5 to run the application. When Internet Explorer appears, enter some values in the text boxes and check out the application. The Web application is functionally equivalent to the Windows loan application you developed at the beginning of this chapter. Yet its user interface runs in the browser, but the calculations take place on the server (the machine to which the clients connect to request the WebLoanForm.aspx Web page). Every time you click the Monthly Payment button on the page, the page is posted to the server. The browser transmits the values on the various controls back to the server. The server processes these values (actually, it executes the event handler you wrote) and creates a new page, which is sent to the client. This page includes the value of the monthly payment. Web applications are discussed in detail later in this book; with this example I wanted to demonstrate the similarities between Windows forms and Web forms and how the same code works with both types of applications.
Working with Multiple Forms
Let’s return to Windows applications. Few applications are built on a single form. Most applications use two, three, or more forms, which correspond to separate sections of the application. In this section, we are going to build an application that uses three forms and lets the user switch among them at will. You’ll see how to write an application that opens multiple windows on the Desktop. In Chapter 4, we’ll explore in depth the topic of building Windows applications with multiple forms. In this chapter, we’ll build a simple example of a multiform application by combining the math and financial calculators we built earlier in the chapter.
The way to combine the two applications is to create a new form, which will become the switching point for the two calculators. The user will be able to invoke either of the two calculators by clicking a button on the new form. Let’s design an application that combines the forms of the two projects.
Start a new project and call it Calculators. The project’s form will become the switching point between the other two forms, and it’s shown in Figure 2.10. Start by renaming the new form from Form1 to CalculatorsForm. To design it, add two Button controls and name them bttnMath and
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

64 |
Chapter 2 VISUAL BASIC PROJECTS |
bttnLoan. Then set their Text properties to Simple Math and Simple Loan, respectively. As you can guess, all you have to do now is add the code to invoke each of the existing forms from within each button’s Click event handler. Add a third button on the form, call it bttnGame, and later you can add an action game to the Calculators project.
Figure 2.10
The main form of the Calculators application
At this point, we must add the forms of the MathCalculator and LoanCalculator projects into the new project. Right-click the name of the project, and from the context menu, select Add Existing Item. In the dialog box that appears, select the item MathForm.vb in the MathCalculator project’s folder. Do the same for the LoanForm of the LoanCalculator project. The Calculators project now contains three forms.
If you run the project now, you will see the Calculators form, but clicking its button won’t bring up the appropriate form. Obviously, you must add a few lines of code in the Click event handler of each button to invoke the corresponding form. To display one form from within another form’s code, you must create an object that represents the second form and then call its Show method. The code behind the Simple Math button is shown in Listing 2.11.
Listing 2.11: Invoking the Math Calculator
Private Sub bttnMath_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles bttnMath.Click Dim calcForm As New CalculatorForm
calcForm.Show() End Sub
The calcForm variable is an object variable that represents the CalculatorForm form of the Calculators application. The name of the form is actually used as a data type, and this requires some explanation. The form is implemented as a Class and therefore you create objects of this type.
The Dim statement creates a new instance of the form, and the Show method loads and displays the form. If you run the project now, you’ll see the main form, and if you click the first button, the math calculator’s form will appear. If you click the same button again, another instance of the form will appear. What can we do to prevent this? We would like to display the CalculatorForm initially and then simply show it, but not load another instance of the form. The answer is to move the declaration of the calcForm variable outside the event handler, into the Form’s declaration section. The variable is declared once, and all the procedures in the form can access its members. Variables declared in an event handler take effect only in the event handler in which they were declared, and that’s why at this point, every time you click a button, a new instance of the corresponding form is
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

WORKING WITH MULTIPLE FORMS 65
created and displayed. If the variable calcForm points to a single instance of the CalculatorForm, then the form will be displayed every time we click the Simple Math button, but no new instance of it will be created. You’ll find out more about the scope of variables in the following chapter.
When one of the two calculators is displayed, it doesn’t automatically become the active form. The active form is the one that has the focus, and this is the main form of the application. To work with a calculator, you must click the appropriate form to make it active. To activate the most recently displayed form from within another form’s code, we’ll use the Activate method of the Form object. Rewrite the Click event handlers of the two buttons on the form as shown in Listing 2.12 (the listing shows the entire code of the form, so that you can see the declarations of the two variables that represent the forms of the application).
Listing 2.12: The Calculators Project
Public Class CalculatorsForm Inherits System.Windows.Forms.Form
Dim calcForm As New CalculatorForm() Dim loanForm As New loanForm()
Private Sub bttnMath_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles bttnMath.Click calcForm.Show()
calcForm.Activate() End Sub
Private Sub bttnLoan_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles bttnLoan.Click loanForm.Show()
loanForm.Activate() End Sub
End Class
Notice the statement that declares the loanForm variable: the variable has the same name as the data type, but this is no problem. It goes without saying that the name of the variable can be anything. Our next task is to specify which form will be displayed when we start the application. Rightclick the Calculators project name and, in the context menu, select Properties. On the Calculators Property Pages dialog box (Figure 2.11) is a ComboBox named StartUp Object. Expand it and you will see the names of all the forms in the project. Select the name of form you want to appear when the program starts, which is the CalculatorsForm.
The code behind the Play A Game button should also call the Show method of another form, but it doesn’t. I regret not developing a game for your enjoyment, but I did implement a fun feature. When you click this button, it jumps to another place on the form. The button’s Click event handler is shown next:
Private Sub bttnGame_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles bttnGame.Click bttnGame.Left = Rnd() * Me.Width * 0.8
bttnGame.Top = Rnd() * Me.Height * 0.8 End Sub
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

66 |
Chapter 2 VISUAL BASIC PROJECTS |
Figure 2.11
Open the Project Properties dialog box to specify the startup object.
This subroutine manipulates the Left and Top properties of the control to move the button to a different position. The Rnd() function returns a random value between 0 and 1. To calculate the horizontal position, the code multiplies the random value by the width of the form (actually, 80 percent of the width). The vertical position is calculated in a similar manner.
Each Visual Basic project is made up of files that are all listed in the Solution Explorer window. Each project contains quite a few files in addition to the Form files, and they’re all stored in a single folder, which is named after the project. If you open the Calculators folder (Figure 2.12), you will see that it contains the CalculatorForm and LoanForm forms. These are copies of the original forms of their corresponding applications. When you add an existing item to a project, VB makes a copy of this item in the project’s folder.
Figure 2.12
The components of the Calculators project
To move a project to another location, just move the project’s folder there. To create a copy of the project, just copy the project’s folder to a different location.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |