
- •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 6
Basic Windows Controls
In the previous chapters, we explored the environment of Visual Basic and the principles of event-driven programming, which is the core of VB’s programming model. In the process, we briefly explored a few basic controls through the examples. The .NET Framework provides many more controls, and all of them have a multitude of properties. Most of the properties have obvious names, and you can set them either from the Properties window or from within your code.
This chapter explores several of the basic Windows controls in depth. These are the controls you’ll be using most often in your applications because they are the basic building blocks of the Windows user interface.
Rather than look at controls’ background and foreground color, font, and other trivial properties, we’ll look at the properties unique to each control and how these properties are used in building a user interface.
Note This chapter doesn’t present every property and every method of the basic Windows controls. That would take another book, and its value would be questionable. Most properties are quite simple to use and easy to understand (and then there are some you’ll never use). This chapter focuses on the unique properties, methods, and events of each control you need to know, in order to use them in your user interface.
The TextBox Control
The TextBox control is the primary mechanism for displaying and entering text and is one of the most common elements of the Windows user interface. The TextBox control is a small text editor that provides all the basic text-editing facilities: inserting and selecting text, scrolling if the text doesn’t fit in the control’s area, and even exchanging text with other applications through the Clipboard.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

242 Chapter 6 BASIC WINDOWS CONTROLS
VB6 VB.NET
The VB.NET TextBox control is very similar to the one in VB6, with a major improvement. The old TextBox control couldn’t handle large chunks of text. It could handle up to 32K characters, and this was a serious limitation. The new TextBox control can hold more than 2 billion characters, which is more than you care to read in a single session.
The WordWrap property allows you to specify whether the control will wrap text lines as they approach the width of the control. In the old version of the control, the ScrollBars property determined whether the control wraps the text. Without a horizontal ScrollBar, the text was wrapped automatically. Now, you can enter long lines of text even if no horizontal scroll bar is present.
Another feature of the new TextBox control is that it allows you to access individual lines of text through the Lines property. The Lines property is a string array, and each element of the array holds a text line. Lines(0) is the first line, Lines(1) is the second line, and so on. The number of text lines on the control is given by the expression Lines.Length.
Finally, the properties that let you select or manipulate text—the SelStart, SelLength, and SelText proper- ties—have changed names. They’re now called SelectionStart, SelectionLength, and SelectedText. The Alignment property, which specifies the alignment of the text on the control, is now called TextAlignment. The AppendText method lets you add text to the control, and it’s much faster than the equivalent statement
TextBox1.Text = TextBox1.Text & newLine
The text box is an extremely versatile data-entry tool that can be used for entering a single line of text, such as a number or a password, or for entering simple text files. Figure 6.1 shows a few typical examples created with the TextBox control. All the boxes in Figure 6.1 contain text—some a single line, some several lines. The scroll bars you see in some text boxes are part of the control. You can specify which scroll bars (vertical and/or horizontal) will appear on the control, and the appropriate scroll bars are attached to the control automatically whenever the control’s contents exceed the visible area of the control.
With the exception of graphics applications, the TextBox control is the bread and butter of any Windows application. By examining its properties and designing a text editor based on the TextBox control, you’ll see that most of the application’s functionality is already built into the control.
Figure 6.1
Typical uses of the
TextBox control
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

THE TEXTBOX CONTROL 243
Basic Properties
Let’s start with the properties that determine the appearance and, to some degree, the functionality of the TextBox control; these can be set through the Properties window. Then, we’ll look at the properties that allow you to manipulate the control’s contents. Let me mention quickly the TextAlign property, which sets (or returns) the alignment of the text on the control and can be Left, Right, or Center. The TextBox control doesn’t allow you to format text, but you can set the font in which the text will be displayed with the Font property, as well as the control’s background color with the BackColor property. If you want to display a background image, use the BackImage property and assign to it the path of the file with the desired image.
MultiLine
This property determines whether the TextBox control will hold a single line or multiple lines of text. By default, the control holds a single line of text. To change this behavior, set the MultiLine property to True.
ScrollBars
This property controls the attachment of scroll bars to the TextBox control if the text exceeds the control’s dimensions. Single-line text boxes can’t have a scroll bar attached, even if the text exceeds the width of the control. Multiline text boxes can have a horizontal or a vertical scroll bar, or both.
Scroll bars can appear in multiline text boxes even if they aren’t needed or the text doesn’t exceed the dimensions of the control.
If you attach a horizontal scroll bar to the TextBox control, the text won’t wrap automatically as the user types. To start a new line, the user must press Enter. This arrangement is useful in implementing editors for programs in which lines must break explicitly. If the horizontal scroll bar is missing, the control inserts soft line breaks when the text reaches the end of a line, and the text is wrapped automatically. You can change the default behavior by setting the WordWrap property.
WordWrap
This property determines whether the text is wrapped automatically when it reaches the right edge of the control. The default value of this property is True. If the control has a horizontal scroll bar, however, you can enter very long lines of text. The contents of the control will scroll to the left, so that the insertion point is always visible as you type. You can turn off the horizontal
scroll bar and still enter long lines of text; just use the left/right arrows to bring any part of the text into view.
This feature may seem dubious at first, but you’ll find it useful when you resize the control. By the way, it’s very easy to resize the control so that it always fills the form, with the Dock property (see section “Anchoring and Docking” in Chapter 5). If the text is a program listing, like the one shown in Figure 6.2, or a list of numbered items, you don’t want the text to wrap at any point.
You’d rather force users to open up the form so that the entire width of the text is visible across the control. You can experiment with the WordWrap and ScrollBars properties in the TextPad application, which is described later in this chapter.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

244 Chapter 6 BASIC WINDOWS CONTROLS
Figure 6.2
Turn off the WordWrap property to display program listings or other lines that shouldn’t break arbitrarily.
Notice that the WordWrap property has no effect on the actual line breaks. The lines are wrapped automatically, and there are no hard breaks (returns) at the end of each line. Open the TextPad project, enter a long paragraph, and resize the window. The text will be automatically adjusted to the new width of the control. Then select it and copy it by pressing Ctrl+C. Switch to Word, or another word processor, and paste it. You will see that the text is copied as a single paragraph, without additional hard breaks. The lines will break according to the size of the container and will be re-broken when the control is resized.
As you can understand, when WordWrap is set to True, there’s no reason to attach a horizontal scroll bar to the control. Even if you set the ScrollBars property to Horizontal, this setting will be ignored.
AcceptsReturn, AcceptsTab
These two properties specify how the TextBox control reacts to the Return (Enter) and Tab keys. The Enter key activates the default button on the form, if there is one. The default button is usually an OK button that can be activated with the Enter key, even if it doesn’t have the focus. In a multiline TextBox control, however, we want to be able to use the Enter key to change lines. The default value of this property is True, so that pressing Enter creates a new line on the control. If you set it to False, users can still create new lines in the TextBox control, but they’ll have to press Ctrl+Enter. If the form contains no default button, then the Enter key creates a new line regardless of the AcceptsReturn setting.
Most forms that contain text boxes have also a default button, so users can work with the keyboard. Otherwise, they’d be forced to take their hands off the keyboard, use the mouse to click a button, and then return to the keyboard—or press the Tab button repeatedly to move the focus to one of the buttons.
Tip This is a very important issue in designing practical user interfaces. You shouldn’t force your users to switch between the keyboard and the mouse all the time. Follow the Windows standards (the Enter key for the default button, the Tab key to move from one control to the next, and shortcuts) to make sure that your application can be used without the mouse. Data-entry operators would rather work without the mouse at all.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |