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

294 Chapter 7 MORE WINDOWS CONTROLS
This statement returns an integer value that represents the color Navy. This value, however, is negative. The reason for that is that the first byte in the color value represents the transparency of the color. To get the value of the color, you must take the absolute value of the integer value returned by the previous expression. To create an array of integers that represent color values, use a statement like the following:
Dim colors() As Integer = {Math.Abs(Color.Gray.ToARGB), _
Math.Abs(Color.Navy.ToARGB), _
Math.Abs(Color.Teal.ToARGB)}
Now you can assign the colors array to the CustomColors property of the control, and they will appear in the Custom Colors section of the Color dialog box. The three colors of the same code are the custom colors shown in Figure 7.2.
SolidColorOnly
Indicates whether the dialog box will restrict users to selecting solid colors only. This setting should be used with systems that can display only 256 colors.
The Font Dialog Box
The Font dialog box, shown in Figure 7.3, lets the user review and select a font and its size and style. Optionally, the user can also select the font’s color and even apply the current dialog-box settings to the selected text on a control of the form without closing the dialog box, by clicking the Apply button on the Font dialog box.
Figure 7.3
The Font common dialog box
After the user selects a font, its size and style, and possibly some special effects (the text color or the underline attribute), and clicks the OK button, the dialog returns the attributes of the selected font through its properties. In addition to the OK button, there’s an Apply button, which reports the current setting to your application. You can intercept the Click event of the Apply button and adjust the appearance of the text on your form while the common dialog is still visible.
The main property of this control is the Font property, which sets the initially selected font on the control and retrieves the font selected by the user. The following statements display the Font
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

THE COMMON DIALOG CONTROLS 295
dialog box after selecting the current font of the TextBox1 control. When the user closes the dialog box, they retrieve the selected font and assign it to the TextBox control:
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
FontDialog1.Font = TextBox1.Font
If FontDialog1.ShowDialog = DialogResult.OK Then
TextBox1.Font = FontDialog1.Font
End If
End Sub
AllowScriptChange
This property is a Boolean value that indicates whether the Script combo box will be displayed on the Font common dialog. This combo box allows the user to change the current character set and select a non-western language (like Greek, Hebrew, Cyrillic, and so on). The text on which the new font is applied will change to a different language only if the corresponding language has been installed on the system.
AllowSimulations
This property is a Boolean value that indicates whether the dialog box allows the display and selection of simulated fonts.
AllowVectorFonts
This property is a Boolean value that indicates whether the dialog box allows the display and selection of vector fonts.
AllowVerticalFonts
This property is a Boolean value that indicates whether the dialog box allows the display and selection of both vertical and horizontal fonts. Its default value is False, which displays only horizontal fonts.
Color
This property sets or returns the selected font color. The user will see the option to select a color for the selected font only if you set the ShowColor property to True.
FixedPitchOnly
This property is a Boolean value that indicates whether the dialog box allows only the selection of fixed-pitch fonts. Its default value is False, which means that all fonts (fixedand variable-pitch fonts) are displayed on the common dialog.
Font
This property is a Font object. You can set it to the preselected font before displaying the dialog box and assign it to a Font property upon return. The following statements show how to preselect
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

296 Chapter 7 MORE WINDOWS CONTROLS
the font of the TextBox1 control on the Font dialog box and how to change the same control’s font to the one selected by the user on the dialog box:
FontDialog1.Font = TextBox1.Font
If FontDialog1.ShowDialog = DialogResult.OK Then
TextBox1.Font = FontDialog1.Font
End If
You can create a new Font object and assign it to the control’s Font property. The following statements do that:
Dim newFont As Font
newFont = New Font(“Verdana”, 12, FontStyle.Underline) FontDialog1.Font = newFont
FontDialog1.ShowDialog()
The Font object’s constructor is heavily overloaded. The form shown here is among the simpler overloaded forms of the constructor. To apply multiple attributes, combine their names with the Or operator.
The Color property is not part of the Font property. If you allow users to change the font’s color, you must handle this property separately from within your code. To continue the previous example, the following statement sets the color of the new font:
TextBox1.ForeColor = FontDialog1.Color
FontMustExist
This property is a Boolean value that indicates whether the dialog box forces the selection of an existing font. If the user enters a font name that doesn’t correspond to a name in the list of available fonts, a warning is displayed. Its default value is True.
MaxSize, MinSize
These two properties are integers that determine the minimum and maximum point size the user can select. Use these two properties to prevent the selection of extremely large or extremely small font sizes.
ScriptsOnly
This property indicates whether the dialog box allows selection of fonts for Symbol character sets, in addition to the American National Standards Institute (ANSI) character set. Its default value is True.
ShowApply
This property is a Boolean value that indicates whether the dialog box provides an Apply button. Its default value is False, so the Apply button isn’t normally displayed. If you set this property to True, you must also program the control’s Apply button—the changes aren’t applied automatically to any of the controls on the current form.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

THE COMMON DIALOG CONTROLS 297
The following statements display the Font dialog box with the Apply button:
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
FontDialog1.Font = TextBox1.Font
FontDialog1.ShowApply = True
If FontDialog1.ShowDialog = DialogResult.OK Then
TextBox1.Font = FontDialog1.Font
End If
End Sub
If you display the Apply button, you must also capture its Click event and process it from within your code. The FontDialog control raises the Apply event every time the user clicks the Apply button. In this event’s handler, you must read the currently selected font and assign it to the TextBox control on the form:
Private Sub FontDialog1_Apply(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles FontDialog1.Apply TextBox1.Font = FontDialog1.Font
End Sub
ShowColor
This property is a Boolean value that indicates whether the dialog box allows the user to select a color for the font.
ShowEffects
This property is a Boolean value that indicates whether the dialog box contains controls to allow the user to specify special text effects, such as strikethrough and underline. The effects are returned to the application as attributes of the selected Font object, and you don’t have to anything special in your application.
The Open and Save As Dialog Boxes
Open and Save As are the two most widely used common dialog boxes, and they’re implemented by the OpenFileDialog and SaveFileDialog controls. Nearly every application prompts the user for a filename, and VB provides two controls for this purpose. The two dialog boxes are nearly identical and most of their properties are common, so we’ll start with the properties that are common to both controls.
When one of the two controls is displayed, it rarely displays all the files in any given folder. Usually the files displayed are limited to the ones that the application recognizes so that users can easily spot the file they want. The Filter property determines which files appear in the Open or Save dialog box (Figure 7.4).
It’s also standard for the Windows interface not to display the extensions of files (although Windows distinguishes files using their extensions). The Save As Type combo box contains the various file types recognized by the application. The various file types can be described in plain English with long descriptive names and without their extensions.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

298 Chapter 7 MORE WINDOWS CONTROLS
Figure 7.4
The Save As dialog box
The extension of the default file type for the application is described by the DefaultExtension property, and the list of the file types displayed in the Save As Type box is described by the Filter property. Both the DefaultExtension and the Filter properties are available in the control’s Properties window at design time. At runtime, you must set them manually from within your code.
To prompt the user for the file to be opened, use the following statements. This dialog box displays the files with the extension .BIN only.
Private Sub bttnSave_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles bttnSave.Click
OpenFileDialog1.DefaultExt = “.BIN”
OpenFileDialog1.AddExtension = True
OpenFileDialog1.Filter = “Binary Files|*.bin”
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Console.WriteLine(OpenFileDialog1.FileName)
End If
End Sub
The following sections describe the properties of the OpenFileDialog and SaveFileDialog controls.
AddExtension
This property is a Boolean value that determines whether the dialog box automatically adds an extension to a filename, if the user omits it. The extension added automatically is the one specified by the DefaultExtension property, which must be set before you call the ShowDialog method.
CheckFileExists
This property is a Boolean value that indicates whether the dialog box displays a warning if the user enters the name of a file that does not exist.
CheckPathExists
This property is a Boolean value that indicates whether the dialog box displays a warning if the user specifies a path that does not exist, as part of the user-supplied filename.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

THE COMMON DIALOG CONTROLS 299
DefaultExtension
This property sets the default extension of the dialog box. Use this property to specify a default filename extension, such as TXT or DOC, so that when a file with no extension is saved, the extension specified by this property is automatically appended to the filename, as long as the AddExtension property is also set to True. The default extension property starts with the period, and it’s a string like “.BIN”.
DereferenceLinks
This property indicates whether the dialog box returns the location of the file referenced by the shortcut or the location of the shortcut itself. If you attempt to select a shortcut on your desktop with the DereferenceLinks property set to False, the dialog box will return to your application a value like C:\WINDOWS\SYSTEM32\lnkstub.exe, which is the name of the shortcut, and not the name of the file represented by the shortcut. If you set the DereferenceLinks property to True, the dialog box will return the actual filename represented by the shortcut, which you can use in your code.
FileName
This property is the path of the file selected by the user on the control. If you set this property to a filename before opening the dialog box, this value will be the proposed filename. The user can click OK to select this file, or select another one on the control. Read this property from within your code only if the control was closed with OK button. If the user closed it with the Cancel button, you should ignore the setting of this value. The two controls provide another related property, the FileNames property, which returns an array of filenames. To find out how to allow the user to select multiple files, see the discussion of the MultipleFiles and FileNames properties under “VB.NET at Work: Multiple File Selection” at the end of this section.
Filter
This property is used to specify the type(s) of files displayed on the dialog box. To display text files only, set the Filter property to “Text files|*.txt”. The pipe symbol separates the description of the files (what the user sees) from the actual extension (how the operating system distinguishes the various file types).
If you want to display multiple extensions, such as BMP, GIF, and JPG, use a semicolon to separate extensions with the Filter property. The string “Images|*.BMP;*.GIF;*.JPG” displays all the files of these three types when the user selects Images in the Save As Type box.
Don’t include spaces before or after the pipe symbol because these spaces will be displayed with the description and Filter values. In the Open common dialog of an image-processing application, you’ll probably provide options for each image file type, as well as an option for all images:
OpenFileDialog1.Filter = “Bitmaps|*.BMP|GIF Images|*.GIF|JPEG” & _
“Images|*.JPG|All Images|*.BMP;*.GIF;*.JPG”
The Open dialog box has four options, which determine what appears in the Save As Type box (see Figure 7.5).
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

300 Chapter 7 MORE WINDOWS CONTROLS
Figure 7.5
Displaying multiple file types in the Open dialog box
FilterIndex
When you specify more than one filter for the Open dialog box, the filter specified first in the Filter property becomes the default. If you want to use a Filter value other than the first one, use the FilterIndex property to determine which filter will be displayed as the default when the common dialog is opened. The index of the first filter is 1, and there’s no reason to ever set this property to 1. If you want to use the Filter property value of the example in the preceding section and set the FilterIndex property to 2, the Open dialog box will display GIF files by default.
InitialDirectory
This property sets the initial directory (folder) in which files are displayed the first time the Open and Save dialog boxes are opened. Use this property to display the files of the application’s folder or to specify a folder in which the application will store its files by default. If you don’t specify an initial folder, it will default to the last folder where the dialog box opened or saved a file. It’s also customary to set the initial folder to the application’s path, with the following statement:
OpenFileDialog1.InitialDirectory = Application.ExecutablePath
The expression Application.ExecutablePath returns the path in which the application’s executable file resides. You can also create a default data folder for the application during installation and use this folder’s name as the initial directory.
RestoreDirectory
Every time the Open and Save dialog boxes are displayed, the current folder is the one selected by the user the last time the control was displayed. The RestoreDirectory property is a Boolean value that indicates whether the dialog box restores the current directory before closing. Its default value is False, which means that the initial directory is not restored automatically. The InitialDirectory property overrides the RestoreDirectory property.
ValidateNames
This property is a Boolean value that indicates whether the dialog box accepts only valid Win32 filenames. Its default value is True, and you shouldn’t change it.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

THE COMMON DIALOG CONTROLS 301
Tip The following four properties—FileNames, MultiSelect, ReadOnlyChecked, and ShowReadOnly—are properties of the OpenFileDialog control only.
FileNames
If the Open dialog box allows the selection of multiple files (see the later section “VB.NET at Work: Multiple File Selection”), the FileNames property contains the pathnames of all selected files. FileNames is a collection, and you can iterate through the filenames with an enumerator. See the MultipleFiles application for an example of iterating through the collection of the selected files. This property is unique to the OpenFileDialog control.
MultiSelect
This property is a Boolean value that indicates whether the user can select multiple files on the dialog box. Its default value is False, and users can select a single file. When the MultiSelect property is True, the user can select multiple files, but they must all come from the same folder. You can’t allow the selection of multiple files from different folders. This property is unique to the OpenFileDialog control.
ReadOnlyChecked
This property is a Boolean value that indicates whether the Read-Only check box is initially selected when the dialog box first pops up (the user can clear this box to open a file in read/write mode). You can set this property to True only if the ShowReadOnly property is also set to True. This property is unique to the OpenFileDialog control.
ShowReadOnly
This property is a Boolean value that indicates whether the Read-Only check box is available. If this check box appears on the form, the user can check it so that the file will be opened as read-only. Files opened as read-only shouldn’t be saved onto the same file—you can prompt the user for a new filename, but you shouldn’t save them with the same filename. This property is unique to the OpenFileDialog control.
VB.NET at Work: The OpenFile and SaveFile Methods
The OpenFileDialog control exposes the OpenFile method, which allows you to quickly open the selected file. Normally, after retrieving the name of the file selected by the user, you must open this file for reading (in the case of the Open dialog box) or writing (in the case of the Save dialog box).
The topic of reading from, or writing to, files is discussed in detail in Chapter 13. In this section, I’ll show you how to quickly read the selected file through the OpenFileDialog control’s OpenFile method.
When the OpenFile method is applied to the Open dialog box, the file is opened with read-only permission. The same method can be applied to the Save dialog box, in which case the file is opened with read-write permission. The OpenFile method is demonstrated by the OpenMethod project, whose main form is shown in Figure 7.6.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

302 Chapter 7 MORE WINDOWS CONTROLS
Figure 7.6
The main form of the OpenMethod project
The following code segment demonstrates how to open a text file with the OpenFile method, read its contents, and display it on a TextBox control. The code displays the Open dialog box and then calls the control’s OpenFile method to open the file and read it. Listing 7.1 is code behind the Open And Read Text File button on the form.
Listing 7.1: The OpenFile Method of the OpenFileDialog Control
Private Sub readTextFile_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles readTextFile.Click OpenFileDialog1.ShowDialog()
Dim str As System.IO.Stream str = OpenFileDialog1.OpenFile
Dim txt As New System.Text.StringBuilder() Dim buffer(1000) As Byte
Dim numBytesToRead As Integer = CInt(str.Length) Dim numBytesRead As Integer = 0
Dim n As Integer
While (numBytesToRead > 0)
n = str.Read(buffer, 0, 1000) Console.WriteLine(n.ToString & “read”) If n = 0 Then
Exit While End If
Dim i As Integer
For i = 0 To n txt.Append(Chr(buffer(i)))
Next numBytesRead += n
numBytesToRead -= n End While
str.Close()
TextBox1.Text = txt.ToString End Sub
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

THE COMMON DIALOG CONTROLS 303
The code reads the file 1,000 characters at a time and appends the characters to a StringBuilder variable (this type of variable is especially efficient for manipulating strings, and you’ll learn more about it in Chapter 12). The Read method of the Stream object reads 1,000 characters and stores them to the buffer array. Then the characters of the array are appended to a StringBuilder variable, the txt variable, which is finally displayed on the TextBox control.
VB.NET at Work: Multiple File Selection
The Open dialog box allows the selection of multiple files. This option isn’t very common, but it can come in handy in situations when you want to process files en masse. You can let the user select many files and then process them one at a time. Or you may wish to prompt the user to select multiple files to be moved or copied.
To allow the user to select multiple files on the Open dialog box, set the MultiSelect property to True. The user can then select multiple files with the mouse by holding down the Shift or Ctrl key. The names of the selected files are reported by the property FileNames, which is an array of strings. The FileNames array contains the pathnames of all selected files, and you can iterate through them as you would iterate through the elements of any array.
In this chapter’s folder on the CD, you’ll find the MultipleFiles project, which demonstrates the use of the FileNames property. The application’s form is shown in Figure 7.7. The button at the top of the form opens a File dialog box, where you can select multiple files. After closing the dialog box by clicking the Open button, the application displays the pathnames of the selected files in the ListBox control.
Figure 7.7
The MultipleFiles project lets the user select multiple files on an Open dialog box.
The code behind the Open Files button is shown in Listing 7.2. In this example, I’ve used the array’s enumerator to iterate through the elements of the FileNames array. You can use any of the methods discussed in Chapter 3 to iterate through the array.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |