- •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
326 Chapter 7 MORE WINDOWS CONTROLS
If selStart = 0 Then
MsgBox(“No more matches”)
Exit Sub
End If
EditorForm.RTFBox.Select(selStart - 1, txtSearchWord.Text.Length)
EditorForm.RTFBox.ScrollToCaret()
End Sub
Notice that both event handlers call the ScrollToCaret method to force the selected text to become visible—should the Find method locate the desired string outside the visible segment of the text.
Summary
This chapter concludes the presentation of the Windows controls you’ll be using in building typical applications. There are a few more controls on the Toolbox that will be discussed in later chapters, and these are the rather advanced controls, like the TreeView and ListView controls. In addition, there are some rather trivial controls, which aren’t used as commonly as the basic controls. The trivial controls will not be discussed in this book. Instead, we’re going to move to some really exciting topics, like how to build custom classes and custom Windows controls.
Classes are at the core of VB.NET and extremely powerful. For the first time, VB classes support inheritance, which means you can extend existing classes, or existing Windows controls. You’ll learn how to build your own classes and inherit existing ones in the following chapter. Then, you’ll learn about building custom controls. Like classes, controls can also be inherited, and you’ll see how easy it is to extend the functionality of existing controls by adding new members.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
Part II
Rolling Your
Own Objects
In this section:
Chapter 8: Building Custom Classes
Chapter 9: Building Custom Windows Controls
Chapter 10: Automating Microsoft Office Applications
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
Chapter 8
Building Custom Classes
Classes are at the very heart of Visual Studio. Just about everything you do with VB.NET is a class, and you already know how to use classes. The .NET Framework itself is an enormous compendium of classes, and you can import any of them into your applications. You simply declare a variable of the specific class type, initialize it, and then use it in your code. As you have noticed, even a Form is a Class, and it includes the controls on the form and the code behind them. All the applications you’ve written so far are enclosed in a set of Class…End Class statements.
When you create a variable of any type, you’re creating an instance of a class. The variable lets you access the functionality of the class through its properties and methods. Even the base data types are implemented as classes (the System.Integer class, System.Double, and so on). An integer value, like 3, is actually an instance of the System.Integer class, and you can call the properties and methods of this class using its instance. Expressions like 3.MinimumValue and
#1/1/2000#.Today are odd, but valid.
In this chapter, you’ll learn how to build your own classes, which you can use in your projects or pass to other developers. Classes are used routinely in team development. If you’re working in a corporate environment, where different programmers code different parts of an application, you can’t afford to repeat work that someone else has done already. You should be able to get their code and use it in your application as is. That’s easier said than done, because you can guess what will happen as soon as a small group of programmers start sharing code. They’ll end up with dozens of different versions for each function, and every time they upgrade a function they will most likely break the applications that were working with the old version. Or, each time they revise a function, they must update all the projects using the old version of the function and test them. It just doesn’t work.
The major driving force behind object-oriented programming is code reuse. Classes allow you to write code that can be reused in multiple projects. You already know that classes don’t expose their source code. In other words, you can’t see the code in a class, and therefore you can’t affect any other projects that use the class. You also know that classes implement complicated operations and make these operations available to programmers through properties and methods. The Array class exposes a Sort method, which sorts its elements. This is not a simple operation, but fortunately you don’t have to know anything about sorting. Someone else has done it for you and made this functionality available to your applications. This is called encapsulation. Some functionality has
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
330 Chapter 8 BUILDING CUSTOM CLASSES
been built into the class (or encapsulated into the class), and you can access it from within your applications with a simple method call.
The 3,500 (or so) classes that come with the .NET Framework give you access to all the objects used by the operating system. All you have to do is use them in your application. You don’t have to see the code, and you don’t have to know anything about sorting to sort your arrays, just as you don’t need to know anything about encryption to encrypt a string with the System.Security.Cryptography class. In effect, you’re reusing code that Microsoft has already written. As you will see, it is also possible to extend these classes by adding custom members, and even override existing members. When you extend a class, you create a new class based on an existing one. Projects using the original class will keep seeing the original class, and they will work fine. New projects that see the derived class will also work.
In this chapter, you’ll learn how to create your own classes and share them with other programmers. This is one of the most improved areas of VB.NET, which is the first truly object-oriented version of Visual Basic. Most of the new functionality comes from the new techniques for implementing classes. Once you understand how classes are implemented and how to exploit features like inheritance, you’ll understand the topics discussed in earlier chapters a lot better. If you still have questions regarding the object-oriented features of the language, like the methods and properties exposed by the various data types, there’s a good chance that you’ll find the answers here. This chapter is not as much about techniques as it is about a good understanding of how classes work and why features like inheritance are really needed in a modern language—and, of course, why you shouldn’t go overboard with inheritance.
What Is a Class?
A class is a program that doesn’t run on its own; it must be used by another application. The way we invoke a class is by creating a variable of the same type as the class. Then, we exploit the func-
tionality exposed by the class by calling the members of the class through this variable. The methods and properties of the class, as well as its events, constitute the class’s interface. It’s not a visible interface, like the ones you’ve learned to design so far, and the class doesn’t interact directly with the user. To interact with the class, the application uses the class’s interface, just as users will be interacting with your application through its visual interface.
Until now, you have learned how to use classes. Now’s the time to understand what goes on behind the scenes when you interact with a class and its members. Behind each object, there’s a class. When you declare an array, you’re invoking the System.Array class, which contains all the code for manipulating arrays. Even when you declare a simple integer variable, you’re invoking a class, the System.Integer class. This class contains the code that implements the various properties (such as MinValue and MaxValue) and methods (such as ToString) of the Integer data type. The first time you use an object in your code, you’re instantiating the class that implements this object. The class is loaded into memory, initializes its variables, and is ready to execute. An instance of the class is ready for you to use.
Classes are very similar to Windows controls, only they don’t have a visible interface. Controls are instantiated when you place them on a form; classes are instantiated when you use a variable of the same type—and not when you declare the variable with the Dim statement. To use a control,
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |