- •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
530 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES
In this chapter, we’ll explore the members of the String and StringBuilder classes, which handle strings, and the members of the DateTime and TimeSpan classes, which handle dates and time. As I go along, I will mention the equivalent VB functions for the readers already familiar with VB6. If you’re porting old VB applications to VB.NET, the string and date functions of VB6 still work with VB.NET, but you should gradually replace them with the newer classes. If you’ve written applications that manipulate strings extensively, you should take the time to replace the older string functions with the equivalent methods of the StringBuilder class.
Handling Strings and Characters
The new Framework provides two classes for manipulating text: the String and the StringBuilder classes. The String object represents fixed-length strings, which you can’t edit. Once you assign a value to a String object, that’s it. You can examine the string, locate words in it, parse it, but you can’t edit it. The String class also exposes methods like the Replace and Remove methods, which replace a section of the string with another or remove a range of characters from the string. These methods, however, don’t act on the string directly: they replace or remove parts of the original string and then return the result as a new string.
The StringBuilder class is similar to the String class: it stores strings, but it can manipulate them in place. The distinction between the two classes is that the String class is for static strings, while the StringBuilder class is for dynamic strings. Use the String class for strings that don’t change frequently in the course of an application and the StringBuilder class for strings that grow and shrink frequently. The two classes expose similar methods, but the String class’s methods return new strings; if you need to manipulate large strings extensively, using the String class may fill the memory quite fast.
Any code that manipulates strings must also be able to manipulate individual characters. In previous versions of Visual Basic, characters were indistinguishable from strings; they were one-character strings. VB.NET introduces the Char class, which not only stores characters but also exposes numerous methods for handling characters. Both the String and StringBuilder classes provide methods for storing strings into arrays of characters, as well as converting character arrays into strings. After extracting the individual characters from a string, you can process them with the members of the Char class. We’ll start our discussion of text-handling features of VB.NET with an overview of the Char data type, and we’ll continue with the other two major components, the String and StringBuilder classes.
VB6 VB.NET
The Char class is new to VB.NET, and it exposes numerous methods for handling characters. You will find this data type especially useful in validating user-supplied strings, as you no longer need to write code to figure out whether a character is a digit or letter, a special character, and so on. There are now methods you can call to find out the type of character stored in a Char variable.
The StringBuilder is also new to VB.NET. The old string functions of Visual Basic are now implemented as methods of the String and StringBuilder classes.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
HANDLING STRINGS AND CHARACTERS 531
The Char Class
The Char data type stores characters as individual, double-byte (16-bit), Unicode values, and it exposes methods for classifying the character stored in a Char variable. You can use methods like IsDigit and IsPunctuation on a Char variable to determine its type, and other similar methods can simplify your string validation code.
To use a character variable in your application, you must declare it with a statement like the following one:
Dim ch As Char = “A”
You can also initialize it by setting the variable to a character:
Dim ch As Char = CChar(“A”)
The expression “A” represents a string, even though it contains a single character. Everything you enclose in double quotes is a string. To convert it to a character, you must cast it to the Char type. If the Strict option is off (which is the default value), you need not perform the conversion explicitly.
If the Strict option is on, you must use the CChar() or CType() function to convert the string in the double quotes to a character value, as shown in the second example line. You can also pass a string to CChar() function. It will convert the first character of the string to a Char type and ignore the following characters. The CType() function can convert an object to a character.
Properties
The Char class provides two trivial properties, MaxValue and MinValue. They return the largest and smallest character values you can represent with the Char data type.
Methods
The Char data type exposes methods for handling characters. As you will see, the String and StringBuilder classes expose the Chars property, which returns individual characters in the string, and you can apply any of the methods discussed here to a variable of the Char type.
All the methods discussed in the following sections have the same syntax. They accept either a single argument, which is the character they act upon, or a string and the index of a character in the string on which they act. The IsDigit() method, for example, has two forms, which are:
Char.IsDigit(char)
Char.IsDigit(string, 3)
The first statement acts on a character variable, while the second form acts on the third character of the specified string. Both methods return True if the specified character is a numeric digit, False otherwise.
With a few exceptions, the methods of the Char class are shared. This means that you can call them without having to create an instance of the class. As you saw, the IsDigit method accepts as argument a character and doesn’t act on a Char variable. If the ch variable represents a character, you can find out whether the character is a digit with either of the following statements:
ch.IsDigit(ch)
Char.IsDigit(ch)
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
532 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES
The first notation isn’t very elegant, so I will use the second notation in the examples of this section. You can even use the following counter-intuitive method of calling IsDigit:
CType(“a”, Char).IsDigit(“4”)
The CType() function returns a character, and you can apply any of the System.Char class’s methods to this character.
GetNumericValue
This method returns a numeric value if called with an argument that is a digit, and the value –1 otherwise. If you call the GetNumericDigit with the argument “5”, it will return the numeric value 5. If you call it with the symbol “@”, it will return the value –1.
GetUnicodeCategory
This method returns a numeric value that is a member of the UnicodeCategory enumeration and identifies the Unicode group to which the character belongs. The Unicode categories group characters into many categories such as math symbols, currency symbols, and quotation marks. Look up the UnicodeCategory enumeration in the documentation for more information.
IsControl
This method returns a True/False value indicating whether the specified character is a control character. The Backspace and Escape keys, for example, are control characters. The second form of the method examines the character at location index in a string and returns True if it’s a control character.
IsDigit
This method determines whether the specified character is a digit. The code segment in Listing 12.1 uses the IsDigit method to find out whether the current character is a digit or a character. You can insert this code in a control’s KeyPress event to process each keystroke.
Listing 12.1: Differentiating Letter from Digit Keystrokes
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress Dim c As Char
c = e.KeyChar
If Char.IsDigit(c) Then
{process c as number }
Else
{process c as character or punctuation symbol } End If
End Sub
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
HANDLING STRINGS AND CHARACTERS 533
The e.KeyChar property returns the character that was pressed by the user and fired the KeyPress event. To reject nonnumeric keys as the user enters text on a TextBox control, use the event handler shown in Listing 12.2.
Listing 12.2: Rejecting Nonnumeric Keystrokes
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As EventArgs) Dim c As Char
c = e.KeyChar
If Not (Char.IsDigit(c) Or Char.IsControl(c)) Then e.Handled = True
End If End Sub
This code ignores any keystrokes that don’t represent numeric digits and are not control characters. Control characters are not rejected, because we want users to be able to edit the text on the control. The Backspace key is captured by the KeyPress event, and you shouldn’t “kill” it. If the TextBox control is allowed to accept fractional values, you should allow the period character as well, by using the following If clause:
Dim c As Char c = e.KeyChar
If Not (Char.IsDigit(c) Or c = “.” Or Char.IsControl(c)) Then e.Handled = True
End If
IsLetter
This method returns a True/False value indicating whether the specified character is a letter. You can write an event handler similar to the one shown in Listing 12.2 using the IsLetter method to accept letters and reject numeric keys and special symbols.
IsLetterOrDigit
This method returns a True/False value indicating whether the specified character is a letter or a digit. The example of the Chars property of the String class shows how to scan an entire string to find out whether it’s made up of letter and digits, or whether it contains symbols as well.
IsLower, IsUpper
This method returns a True/False value indicating whether the specified character is lowercase or uppercase, respectively.
IsNumber
This method returns a True/False value indicating whether the specified character is a number. The IsNumber method takes into consideration hexadecimal digits (the characters 0123456789ABCDEF) in the same way as the IsDigit method does for decimal numbers.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |