
- •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

Chapter 7
More Windows Controls
In this chapter, we’ll continue our discussion of the basic Windows controls with the controls that implement the common dialog boxes and the RichTextBox control.
The Toolbox contains a few more controls, like ToolBar and DateTimePicker, that I won’t discuss in this book. You won’t often need them in your applications, and once you have learned to build user interfaces with the basic Windows controls, you’ll have no problem using the less common ones. The controls I’m not discussing in this book are less elaborate and have a relatively small number of properties and methods.
The .NET Framework provides a set of controls for displaying common dialogs such as Open or Color. Each of these controls encapsulates a large amount of functionality that would take a lot of code to duplicate (in any language). The common dialog controls are an essential part of a Windows application, because they enable you to design user interfaces with the look and feel of a Windows application.
Besides the common dialog boxes, we’ll also explore the RichTextBox control, which is an advanced version of the TextBox. RichTextBox provides all the functionality you’ll need to build a word processor—WordPad is actually built around the RichTextBox control. It’s the only control that can display formatted text, so if your application requires this feature, RichTextBox is your only option. It allows you to format text by mixing any number of fonts and attributes. You can also embed other objects in the document displayed on a RichTextBox, such as images. Sure, the RichTextBox control is nothing like a modern word processor, but it’s a great tool for editing formatted text at runtime.
The Common Dialog Controls
A rather tedious, but quite common, task in nearly every application is to prompt the user for filenames, font names and sizes, or colors to be used by the application. Designing your own dialog boxes for these purposes would be a hassle, not to mention that your applications wouldn’t have the same look and feel of all Windows applications. In fact, all Windows applications use some standard dialog boxes for common operations. Figure 7.1 shows a couple of examples. These dialog boxes are built into the Framework system, and any application can use them.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

290 Chapter 7 MORE WINDOWS CONTROLS
Figure 7.1
The Open and Font common dialog boxes
If you ever want to display an Open or Font dialog box, don’t design it—it already exists. To use it, just place the appropriate common dialog control on your form and activate it from within your code by calling the ShowDialog method.
VB6 VB.NET
In previous versions of VB, there was a single control on the Toolbox for all common dialog controls. VB.NET has a separate control for each common dialog, and there are four such controls on the Toolbox (excluding the ones that apply to printing). The new common dialog controls are the FontDialog, ColorDialog, OpenFileDialog, and SaveFileDialog. The new controls expose a large number of properties that are specific to each dialog box and are a little easier to program than the previous single control. The dialog controls for printing are discussed in detail in Chapter 15.
The common dialog controls are invisible at runtime, and they’re not placed on your forms. You simply add them to the project by double-clicking their icons on the Toolbox. When a common dialog control is added to a project, a new icon appears in the components tray of the form, just below the Form Designer. The following common dialog controls are available on the Toolbox.
OpenFileDialog Lets users select a file to open. It also allows the selection of multiple files, for applications that must process many files at once (change the format of the selected files, for example).
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

THE COMMON DIALOG CONTROLS 291
SaveFileDialog Lets users select or specify a filename in which the current document will be saved.
ColorDialog Lets users select a color from a list of predefined colors, or specify custom colors.
FontDialog Lets users select a typeface and style to be applied to the current text selection. The Font common dialog has an Apply button, which you can intercept from within your code and use to apply the currently selected font to the text without closing the common dialog.
PrintDialog Lets users select and set up a printer (the page’s orientation, the document pages to be printed, and so on).
There are two more common dialog controls, the PrintPreviewDialog and the PageSetupDialog controls. These controls will be discussed in detail in Chapter 15, in the context of VB’s printing capabilities. The PrintDialog control is discussed here because it doesn’t require any printing code. This dialog box simply sets the basic properties of the printout. These properties must be taken into consideration by the printing code of the application, as you will see in Chapter 15.
Using the Common Dialog Controls
To display a common dialog from within your application, you must first add an instance of the appropriate control to your project. Then, you must set basic properties of the control through the Properties window. Most applications set the control’s properties from within the code, because common dialogs interact closely with the application. When you call the Color common dialog, for example, you should preselect a color from within your application and make it the default selection on the control. If you open the Color dialog box to prompt the user for the color of the text on a control, the default selection should be the current setting of the control’s ForeColor property. Likewise, the Save dialog box must suggest a filename when it first pops up, and you must specify the appropriate filename (or, at least, the file’s extension) from within your application’s code.
To display a common dialog box from within your code, you simply call the control’s ShowDialog method, which is common for all controls. As soon as you call the ShowDialog method, the corresponding dialog box appears on-screen and the execution of the program is suspended until the box is closed. Using the Open and Save dialog boxes, the user can traverse the entire structure of their drives and locate the desired filename. When the user clicks the Open or Save button, the dialog box closes and the program’s execution resumes. The code should read the name of the file selected by the user (FileName property) and use it to open the file or to store the current document there.
Here is the sequence of statements used to invoke the Open common dialog and retrieve the selected filename:
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
fileName = OpenFileDialog1.FileName
End If
The common dialogs are nothing more than dialog boxes, and they return a value indicating how they were closed. You should read this value from within your code and ignore the settings of the dialog box if it was canceled.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

292 Chapter 7 MORE WINDOWS CONTROLS
The variable fileName is the full pathname of the file selected by the user. You can also set the FileName property to a filename, which will be displayed when the Open dialog box is first opened. This allows the user to click the Open button to open the preselected file or choose another file.
OpenFileDialog1.FileName = “C:\Documents\Doc1.doc”
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
fileName = OpenFileDialog1.FileName
End If
Similarly, you can invoke the Color dialog box and read the value of the selected color with the following statements:
If ColorDialog1.ShowDialog = DialogResult.OK Then
selColor = ColorDialog1.Color
End If
The ShowDialog method is common to all controls. The Title property is also common to all controls. This property returns or sets the string displayed in the title bar of the dialog box. The default title is the name of the dialog box (e.g., “Color,” Font,” and so on), but you can adjust it from within your code.
The Color Dialog Box
The Color dialog box, shown in Figure 7.2, is one of the simplest dialog boxes. It has a single property, Color, which returns the color selected by the user or sets the initially selected color when the user opens the dialog box. Before opening the Color common dialog with the ShowDialog method, you can set various properties, which are described next.
Figure 7.2
The Color dialog box
The following statements set the selected color of the Color common dialog control, display the control, and then use the color selected on the control to fill the form. First, place a ColorDialog control on the form, and then insert the following statements in a button’s Click event handler:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
ColorDialog1.Color = Me.BackColor
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

THE COMMON DIALOG CONTROLS 293
ColorDialog1.AllowFullOpen = True
If ColorDialog1.ShowDialog = DialogResult.OK Then
Me.BackColor = ColorDialog1.Color
End If
End Sub
AllowFullOpen
Set this property to True if you want users to be able to open up the dialog box and define their own custom colors. The AllowFullOpen property doesn’t open the custom section of the common dialog. It simply enables the Define Custom Colors button on the dialog box. Otherwise, this button is disabled. If you want to fully open the Color dialog box (like the one shown in Figure 7.2) when it first pops up, set the AllowFullOpen property to True. The Define Custom Colors button on the dialog box of Figure 7.2 is disabled because the dialog box is already fully opened.
AnyColor
This property is a Boolean value that determines whether the dialog box displays all available colors in the set of basic colors.
Color
This property is a Color value, and you can set it to any valid color. If you set this property before opening the Color dialog box, the selected color will appear on the control as the preselected color. On return, it’s the color selected by the user on the dialog box.
ColorDialog1.Color = Color.Azure
If ColorDialog1.ShowDialog = DialogResult.OK Then
Me.BackColor = ColorDialog1.Color
End If
CustomColors
This property indicates the set of custom colors that will be shown in the common dialog. The Color dialog box has a section called Custom Colors, where you can display 16 additional custom colors. The CustomColors property is an array of integers that represent colors. To display three custom colors in the lower section of the Color dialog box, use a statement like the following:
Dim colors() As Integer = {222663, 35453, 7888}
ColorDialog1.CustomColors = colors
You’d expect that the CustomColors property would be an array of Color values, but it’s not. You can’t create the array CustomColors with a statement like:
Dim colors() As Color = {Color.Azure, Color.Navy, Color.Teal}
Since it’s awkward to work with numeric values, you should convert color values to integer values with a statement like the following:
Color.Navy.ToARGB
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |