- •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
THE RICHTEXTBOX CONTROL 313
Methods
The first two methods of the RichTextBox control you will learn about are SaveFile and LoadFile:
SaveFile saves the contents of the control to a disk file.
LoadFile loads the control from a disk file.
SaveFile
The syntax of the SaveFile method is
RichTextBox1.SaveFile(path, filetype)
where path is the path of the file in which the current document will be saved. By default, the SaveFile method saves the document in RTF format and uses the RTF extension. You can specify a different format with the second, optional, argument, which can take on the value of one of the members of the RichTextBoxStreamType enumeration, which are described in Table 7.2.
Table 7.2: The RichTextBoxStreamType Enumeration
Format |
Effect |
PlainText |
Stores the text on the control without any formatting |
RichNoOLEObjs |
Stores the text without any formatting and ignores any embedded OLE objects |
RichText |
Stores the formatted text |
TextTextOLEObjs |
Stores the text along with the embedded OLE objects |
UnicodePlainText |
Stores the text in Unicode format |
|
|
LoadFile
Similarly, the LoadFile method loads a text or RTF file to the control. Its syntax is identical to the syntax of the SaveFile method:
RichTextBox1.LoadFile(path, filetype)
The filetype argument is optional and can have one of the values of the RichTextBoxStreamType enumeration. Saving and loading files to and from disk files are as simple as presenting a Save or Open common dialog control to the user and then calling one of the SaveFile or LoadFile methods with the filename returned by the common dialog box.
Note You can’t assign formatted text to the control at design time. The Text property is available at design time, but the text is rendered in the same format. The RTF property isn’t available at design time. To display initially some formatted text on the control, you must either load it from a file with the LoadFile method, or assign the equivalent RTF code to the RTF property at runtime, usually from within the form’s Load event.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
314 Chapter 7 MORE WINDOWS CONTROLS
Select, SelectAll
The Select method selects a section of the text on the control, similar to setting the SelectionStart and SelectionLength properties. The Select method accepts two arguments, which are the location of the first character to be selected and the length of the selection:
RichTextBox1.Select(start, length)
The SelectAll method accepts no arguments and selects all the text on the control.
Advanced Editing Features
The RichTextBox control provides all the text-editing features you’d expect to find in a text-editing application. You can use the arrow keys to move through the text and press Ctrl+C to copy text or Ctrl+V to paste it. To facilitate the design of advanced text-editing features, the RichTextBox control provides the AutoSelectWord property, which controls how the control selects text. If it’s True, the control selects a word at a time.
In addition to formatted text, the RichTextBox control can handle OLE objects. You can insert images in the text by pasting them with the Paste method. The Paste method doesn’t require any arguments; it simply inserts the contents of the Clipboard at the current location in the document.
The RichTextBox control encapsulates undo and redo operations at multiple levels. Each operation has a name (Typing, Deletion, and so on), and you can retrieve the name of the next operation to be undone or redone and display it on the menu. Instead of a simple Undo or Redo caption, you can change the captions of the Edit menu to something like Undo Delete or Redo Typing.
To program undo and redo operation from within your code, you must use the following properties and methods.
CanUndo, CanRedo
These two properties are Boolean values you can read to find out whether an operation can be undone or redone. If they’re False, you must disable the corresponding menu command from within your code. The following statements disable the Undo command if there’s no action to be undone at the time, where EditUndo is the name of the Undo command on the Edit menu:
If RichTextBox1.CanUndo Then
EditUndo.Enabled = True
Else
EditUndo.Enabled = False
End If
These statements appear in the menu item’s Select event handler (not in the Click event handler), because they must be executed before the menu is displayed. The Select event is triggered when a menu is opened. As a reminder, the Click event isn’t fired when you click an item. For more information on programming the events of a menu, see Chapter 5.
UndoActionName, RedoActionName
These two properties return the name of the action that can be undone or redone. The most common value of both properties is the string “typing,” which indicates that the Undo command will delete a number of characters. Another common value is the “delete” string, while some operations
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
THE RICHTEXTBOX CONTROL 315
are named “unknown.” If you change the indentation of a paragraph on the control, this action’s name is “unknown.” It’s likely that more action names will be recognized in future versions of the control.
The following statement sets the caption of the Undo command to a string that indicates the action to be undone:
EditUndo.Text = “Undo “ & Editor.UndoActionName
Undo, Redo
These two methods undo or redo an action. The Undo method cancels the effects of the last action of the user on the control. The Redo method redoes the last action that was undone. Obviously, unless one or more actions have been undone already, the Redo method won’t have any effect.
You will see how the Undo and Redo methods, as well as the related properties, are used in an application in the section “The RTFPad Project,” later in this chapter.
Cutting and Pasting
To cut, or copy, and paste text on the RichTextBox control, you can use the same techniques as with the regular TextBox control. For example, you can replace the current selection by assigning a string to the SelectedText property. The RichTextBox, however, provides useful methods for performing these operations. The methods Copy, Cut, and Paste perform the corresponding operations. The Cut and Copy methods are straightforward and require no arguments. The Paste method accepts a single argument, which is the format of the data to be pasted. Since the data will come from the Clipboard, you can extract the format of the data in the Clipboard at the time and then call the CanPaste method to find out whether the control can handle this type of data. If so, you can then paste them on the control with the Paste method.
This technique requires quite a bit of code, because the Clipboard object doesn’t return the format of the data it holds. You must call the following method of the Clipboard object to find out whether the data is of a specific type and then call the control’s CanPaste method to find out whether it can handle the data:
If Clipboard.GetDataObject.GetDataPresent(DataFormats.Text) Then
RichTextBox.Paste(DataFormats.Text)
End If
This is a very simple case, because we know that the RichTextBox control can accept text. For a robust application, you must call the GetDataPresent method for each type of data your application should be able to handle (you may not want to allow users to paste all types of data that the control can handle).
In the RTFPad project later in this chapter, we’ll use a structured exception handler to allow users to paste anything on the control. If the control can’t handle it, the data won’t be pasted on the control. As you already know, the RichTextBox control can display images along with text. Each image takes up the entire width of the control. You can center it on the page with the usual alignment properties, but you can’t enter text to either side of the image. If you need a control with the functionality of Word, then you can either automate Word from within your VB application (see Chapter 10 for more information on programming Word’s objects) or purchase a third-party control with advanced processing features.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
316 Chapter 7 MORE WINDOWS CONTROLS
Searching in a RichTextBox Control
The Find method locates a string in the control’s text and is similar to the InStr() function. You can use InStr() with the control’s Text property to locate a string in the text, but the Find method is optimized for the RichTextBox control and supports a couple of options that the InStr() function doesn’t. The simplest form of the Find method is the following:
RichTextBox1.Find(string)
The string argument is the string you want to locate in the RichTextBox control. The method returns an integer value that is the location of the first instance of the string in the text. If the specified string can’t be found in the text, the value –1 is returned.
Another, equally simple syntax of the Find method allows you to specify how the control will search for the string:
RichTextBox1.Find(string, searchMode)
The searchMode argument is a member of the RichTextBoxFinds enumeration, which are shown in Table 7.3.
Table 7.3: The RichTextBoxFinds Enumeration
Value |
Effect |
MatchCase |
Performs a case-sensitive search. |
NoHighlight |
The text found will not be highlighted. |
None |
Locates instances of the specified string even if they’re not whole words. |
Reverse |
The search starts at the end of the document. |
WholeWord |
Locate only instances of the specified string that are whole words. |
|
|
Two more forms of the Find method allow you specify the range of the text in which the search will take place:
RichTextBox1.Find(string, start, searchMode)
RichTextBox1.Find(string, start, end, searchMode)
The arguments start and end are the starting and ending locations of the search (use them to search for a string within a specified range only). If you omit the end argument, the search will start at the location specified by the start argument and will extend to the end of the text.
You can combine multiples of the values of the searchMode argument with the OR operator. The default search is case-insensitive, covers the entire document, and highlights the matching text on the control. The RTFPad application’s Find command demonstrates how to use the Find method and its arguments to build a Search & Replace dialog box that performs all the types of text-searching operations you might need in a text-editing application.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |