- •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
480 Chapter 11 STORING DATA IN COLLECTIONS
VB6 VB.NET
All the topics discussed in this chapter are new to VB.NET. Arrays have been around since the first version of Visual Basic, but all the features discussed in this chapter, such as sorting and searching arrays, are new to VB.NET. ArrayLists are also new to VB.NET; they’re dynamic arrays. Another class, the HashTable, is the evolution of a structure that was known as Dictionary in VB5 and VB6, whose elements are identified not by a number, but by a meaningful key. The basic functionality of the HashTable class is practically identical to that of the Dictionary, but the HashTable has more features, including the ability to sort its elements.
The last topic discussed in this chapter is the ability to specify functions for sorting custom objects in a collection. As you will see, it’s quite simple. These functions don’t actually sort the collection; they simply compare two elements. Once you provide this functionality, the Framework takes it from there and uses your custom functions to sort and search the collection. This type of close interaction with the inner workings of the language is a powerful feature, totally new to VB programmers.
Advanced Array Topics
In Chapter 3, we explored the basics of arrays—how to declare arrays, how to access elements by index, and a few more elementary topics. VB.NET supports arrays through the Array class, which exposes a whole lot of functionality that wasn’t there before. The System.Array class is
not inheritable, which means you can’t create custom arrays; the classes under System.Collections are inheritable, and you can customize the other collections discussed in this chapter.
But before we explore the more advanced methods exposed by the Array class, let me remind you about the basic array members that are new to VB.NET arrays. The Length property returns the number of elements in the array. In the case of a multidimensional array, the Length property returns the total number of elements in all dimensions. To find out the number of dimensions in an array, call its Rank property. The index of the first element in an array is zero, and the index of the last element is retrieved by the method GetUpperBound. If the array is multidimensional, you must specify the dimension whose upper bound you wish to read. The expression array.GetUpperBound(0) returns the upper bound of the first dimension, and the expression array.GetUpperBound(array.Rank - 1) returns the number of elements in the last dimension of the array. For more information on these members, see the section “Arrays” in Chapter 3.
Sorting Arrays
The most prominent feature of the Array class is that VB.NET arrays can be sorted and searched. To sort an array, call its Sort method. This method is heavily overloaded and, as you will see, it is possible to sort an array based on the values of another array, or even supply your own custom sorting routines. If the array is sorted, you can call the BinarySearch method to locate an element. If not, you can call the IndexOf and LastIndexOf methods.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
ADVANCED ARRAY TOPICS 481
The simplest form of the Sort method accepts a single argument, which is the name of the array to be sorted:
System.Array.Sort(arrayName)
This method sorts the elements of the array according to the type of its elements. If the array is not strictly typed, the Sort method will fail. The Array class just doesn’t know how to compare integers to strings or dates, so don’t attempt to sort arrays whose elements are not of the same type. If you can’t be sure that all elements are of the same type, use a Try…Catch statement.
Note The Sort method is a reference method. It requires that you supply the name of the array to be sorted as an argument, even when you’re applying the Sort method directly to an array. In other words, the expression arrayName.Sort() is invalid. You must still pass the name of the array as argument to the Sort method: arrayName.Sort(arrayName). I’m using the notation System.Array.Sort(arrayName) because it’s easier to understand. Besides, a statement like
names.Sort(names) just isn’t elegant.
You can also sort a section of the array with the following form of the Sort method:
System.Array.Sort(arrayName, startIndex, endIndex)
where startIndex and endIndex are the indices that delimit the section of the array to be sorted. I don’t see what good a half-sorted array can be, unless you’re dealing with extremely large arrays. Even then, the Sort method is incredibly fast.
An interesting variation of the Sort method sorts the elements of an array according to the values of the elements in another array. Let’s say you have one array of names and another with the matching Social Security numbers. It is possible to sort the array with the names according to their Social Security numbers. This form of the Sort method has the following syntax:
System.Array.Sort(array1, array2)
array1 is the array with the keys, and array2 is the array with the actual elements to be sorted. This is a very handy form of the Sort method. Let’s say you have a list of words stored in one array and their frequencies in another. Using the first form of the Sort method, you can sort the words alphabetically. With this form of the Sort method, you can sort them according to their frequencies (starting with the most common words and ending with the less common ones). The two arrays must be one-dimensional and have the same number of elements. If you want to sort a section of the array, just supply the startIndex and endIndex arguments to the Sort method, after the names of the two arrays.
The SortArrayByLength application, shown in Figure 11.1, demonstrates how to sort an array based on the length of its elements (short elements appear at the top of the array, while longer elements appear near the bottom of the array). First, it populates the array MyStrings with a few strings, then it assigns the lengths of these strings to the matching elements of the array MyStringsLen. The element MyStrings(0) is “Visual Basic”, and the MyStringsLen(0) element’s value is 12. Once the two arrays have been populated, the code sorts the elements of the MyStrings array according to the values of the MyStringsLen array.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
482 Chapter 11 STORING DATA IN COLLECTIONS
Figure 11.1
The SortArray-
ByLength application
The statement that sorts the array is
System.Array.Sort(MyStringsLen, MyStrings)
The code, which also displays the arrays before and after sorting, is shown in Listing 11.1.
Listing 11.1: Sorting an Array According to the Length of Its Elements
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim MyStrings(3) As String
Dim MyStringsLen(3) As Integer
MyStrings(0) = “Visual Basic” MyStrings(1) = “C++” MyStrings(2) = “C#” MyStrings(3) = “HTML”
Dim i As Integer
For i = 0 To UBound(MyStrings) MyStringsLen(i) = len(MyStrings(i))
Next ListBox1.Items.Clear()
ListBox1.Items.Add(“Original Array”) ListBox1.Items.Add(“*************************”) Dim str As Integer
For str = 0 To UBound(MyStrings) |
|
ListBox1.Items.Add(MyStrings(str) & “ |
“ & MyStringsLen(str).ToString) |
Next |
|
ListBox1.Items.Add(“*************************”) |
|
ListBox1.Items.Add(“Array Sorted According to String Length “) |
|
ListBox1.Items.Add(“*************************”) |
|
System.Array.Sort(MyStringsLen, MyStrings) |
|
For str = 0 To UBound(MyStrings) |
|
ListBox1.Items.Add(MyStrings(str) & “ |
“ & MyStringsLen(str).ToString) |
Next |
|
ListBox1.Items.Add(“*************************”)
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
ADVANCED ARRAY TOPICS 483
‘Sort the array twice
ListBox1.Items.Add(“Array Sorted Twice According to String Length “) ListBox1.Items.Add(“*************************”) System.Array.Sort(MyStringsLen, MyStrings)
For str = 0 To UBound(MyStrings)
ListBox1.Items.Add(MyStrings(str) & “ “ & MyStringsLen(str).ToString) Next
ListBox1.Items.Add(“*************************”) End Sub
The output produced by the SortArrayByLength application on the ListBox control is shown here:
Original Array
*************************
Visual Basic 12 C++ 3
C# 2
HTML 4
*************************
Array Sorted According to String Length
*************************
C# 2
C++ 3
HTML 4
Visual Basic 12
*************************
Array Sorted Twice According to String Length
*************************
C# 2
C++ 3
HTML 4
Visual Basic 12
*************************
Notice that the Sort method sorts both the auxiliary array (the one with the lengths of the strings) and the main array. After the call to the Sort method, the first element in the MyStrings array is “C#”, and the first element in the MyStringsLen array is 2. In other words, the Sort method doesn’t simply sort the elements of one array based on the values of the other array. If it did, the elements of the two arrays would no longer match. Because of the way the Sort method operates, you can sort the array multiple times, as demonstrated in Listing 11.1.
The array with the keys that will determine the order of the elements can be anything. If the array to be sorted holds some rectangles, you can create an auxiliary array with the area of the rectangles, and sort the original array according to the area of its rectangles. Likewise, an array of colors can be sorted according to the hue, or the luminance, of each color component, and so on.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |