
- •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 24
Accessing Data on the Web
Chapter 23 was an introduction to ASP.NET, a brand new technology for developing applications for the Web. At the very least, you’ve learned that ASP.NET does a lot behind the scenes to make developing Web applications look surprisingly similar to developing Windows applications. You have also learned the basic differences between a Web and a Windows application and how to access the native ASP.NET objects when you need them. You have also learned the differences between Windows applications and Web applications and how these differences affect the way you code Web applications.
Currently, the single most common type of applications running on the Web is simple applications that interact with databases. It seems as though everybody is publishing their databases on the Web, and most companies do so to sell on the Internet. In this chapter, we’ll build a Web application that demonstrates the basic operations of a typical Web app: search a database, display the results of a search operation, add items to a basket, and finally place an order. We’ll record the order to the database, and we’ll do so in a transaction. It’s not a trivial example, but it’s not very complicated either. We’ll go through all the steps, examine the code line by line, and when you’re done, you’ll have a better understanding of the structure of a Web application, as well as how to access databases through ASP.NET. Of course, I can’t exhaust the topic of accessing data with ASP.NET, but the information in this chapter will help you feel comfortable with the new technology and explore it on your own.
The Data-Bound Web Controls
Like Windows controls, any Web control can be bound to a data source. The interesting databound controls, however, and the ones that are used most often, are the controls that can display multiple items:
DropDownList Similar to a ListBox control that’s dropped to select an item and retracts automatically.
DataList Displays multiple items, each one in its own cell.
DataGrid A grid control that displays one item per row.
Repeater Displays items as templates; you can have different templates for different types of items.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

1048 Chapter 24 ACCESSING DATA ON THE WEB
We’ll look at the first three controls in detail in this chapter. The Repeater control is the most elaborate, and its main advantage is that you can completely customize its appearance through your code. However, you have to design the templates yourself, and the Repeater control doesn’t provide as much built-in functionality.
There are other types of data-bound controls as well, but either they’re simple controls (like the TextBox or CheckBox control) or they’re similar to the DropDownList control. The ListBox, CheckBoxList, and RadioButtonList are very similar to the DropDownList and expose similar properties, so we won’t discuss them here. The DataGrid, DataList, and Repeater controls are the only ones that can display multiple fields, and they’re the most flexible controls. The DropDownList control (and the other ones similar to it) can only display a single column.
To bind a Web control to a DataSet, you must set its DataSource property to the name of the DataSet to which the control will be bound, then call the DataBind method from within the page’s Load event handler, and do that only if the request for the page isn’t a postback. The DataBind method applies to specific controls and also to the current page. When you apply the DataBind method to the page (Me.DataBind), all data-bound controls are populated from their respective DataSets.
The DropDownList control has two more properties, the DataTextField and DataValueField properties. DataTextField is the name of a DataSet column that will populate the control. The DataValueField is the name of a DataSet column that identifies each row (usually the table’s key field). When the user selects an item in the list, we retrieve the value of the DataValueField property and look up the selected row in the database. To display a list of customers on a DropDownList control, you must set the DataTextField property to the column of the DataSet that holds the customer names and the DataValueField to the column with the customer IDs.
You already know how to create the DataSet objects you need to populate your controls. You can use the visual tools (drop the tables on the design surface, configure the DataAdapter, create the DataSet) or create them from within your code. Since the process of creating DataSet (necessary for binding the various Web controls to) is the same as with Windows applications, I will assume you already know how to retrieve data from a database (or use the Query Builder to design your queries visually) and how to store the qualifying rows to a DataSet object. The process is described in detail in Chapter 21.
We’ll start our exploration of data-binding techniques on the Web with a simple example that doesn’t even use a database.
Simple Data Binding
Data-binding Web controls is similar to binding Windows controls and, in some ways, simpler. To begin with, Web controls can be bound to many different data sources, like arrays and ArrayLists. It’s possible to populate an array (or an ArrayList object) in your code and bind a ListBox control to it. The list control will be populated with the elements of the list, and it will report the selected item—an ideal mechanism for lookup tables like product categories or states.
The current implementation of ASP.NET allows the binding of one-dimensional arrays only. Since arrays are no longer the preferred data type for storing sets of data, this isn’t much of a problem. Use an ArrayList and you’ll be able to store any number of fields, other than the one displayed on the control. To bind an array, or an ArrayList object, to a list control, populate the array, then set the control’s DataSource property to the name of the array or the ArrayList, and finally call the
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

THE DATA-BOUND WEB CONTROLS 1049
DataBind method. To demonstrate how to bind an ArrayList to a data-bound control, we’ll build the DataBinding application, whose page is shown in Figure 24.1. The DropDownList control on the left is expanded and contains a few names. When a name is selected in the list, more information about the selected person is shown in the TextBox and RadioButton controls on the same form.
Figure 24.1
The DataBinding
Web application
As you have guessed by now, we’re going to populate an ArrayList object with the data we want to display on the form. Each element of the ArrayList object is a Contact person, based on the class detailed in Listing 24.1.
Listing 24.1: The Contact Class
Class Contact
Dim _ID As Integer
Dim _name As String
Dim _title As String
Dim _company As String
Dim _married As Boolean
Property ID() As Integer
Get
ID = _ID
End Get
Set(ByVal Value As Integer)
_ID = Value
End Set
End Property
Property Name() As String
Get
Name = _name
End Get
Set(ByVal Value As String)
_name = Value
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

1050 Chapter 24 ACCESSING DATA ON THE WEB
End Set
End Property
Property Title() As String
Get
Title = _title
End Get
Set(ByVal Value As String)
_title = Value
End Set
End Property
Property Company() As String
Get
Company = _company
End Get
Set(ByVal Value As String)
_company = Value
End Set
End Property
Property Married() As Boolean
Get
Married = _married
End Get
Set(ByVal Value As Boolean)
_married = Value
End Set
End Property
Public Overrides Function ToString() As String
Return (_name)
End Function
End Class
It’s a lengthy listing, but you should be quite familiar with classes that expose simple properties. The next step is to declare an ArrayList and populate it with data. Here are the declaration of the ArrayList and the statements that add the first item:
Dim Contacts As New ArrayList() Dim c As New Contact()
c.ID = 0
c.Name = “Maria Anders” c.Company = “Alfreds Futterkiste” c.Title = “Sales Representative” c.Married = False Contacts.Add(c)
OK, we’re ready to build the page. Start a new ASP.NET Web application, name it DataBinding, and insert the Contact class’s code from Listing 24.1 and the code that populates the DropDownList control in the form’s Load event (you can open the project on the CD and copy the statements).
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

THE DATA-BOUND WEB CONTROLS 1051
Then place the controls you see in Figure 24.1 on the page. The last step is to bind the DropDownList control to the ArrayList. Enter the following statements in the page’s Load event handler:
If Not Me.IsPostBack Then
DDListName.DataSource = Contacts
DDListName.DataTextField = “Name”
DDListName.DataValueField = “ID”
DDListName.DataBind()
End If
The control is bound to its data source only the first time the page is loaded, not with every postback. If you bind the control every time the page is posted back, the DropDownList control will be populated from scratch and the first element will be selected automatically. Instead, we want the control to maintain its state. You must set the control’s AutoPostBack property to True (so that it will report the SelectedIndexChanged event to the application) and bind it to its data source the first time it’s loaded. After that, every time the user selects an item on the control, the SelectedIndexChanged event will be fired, which will be processed by the application. The processing consists of retrieving the ID of the selected contact and displaying the values of additional fields on the other controls on the Web form.
The Contacts ArrayList, however, is populated with every postback (the statements that populate it are outside the If statement). You’re probably wondering about the efficiency of this approach. Can’t we do something better than having to populate the ArrayList every time the page is posted back? The answer is no (short of storing the entire ArrayList to the Session object). This is the Web, and the client is totally disconnected from the server. An ASP application must retrieve the current status of the session when a client connects and re-create its data source. The only alternative is to store the data in a Session variable, but this object shouldn’t be used for storing tables or excessive amounts of information. A Web application must service a request and then “die.” If you keep it alive (that is, if you maintain a set of local variables for each session), your server will become unresponsive very quickly. A Web application shouldn’t maintain a lot of data between sessions—and an ArrayList is a lot of information. We’ll do the same with DataSets later in this chapter. We’ll grab the data from the database, populate our page, and then close the connection to the database and discard the DataSet.
When the user selects a name on the DropDownList control, the SelectedIndexChanged event is fired. This is event isn’t reported to the server by default; that’s why you had to set the control’s AutoPostBack property to True. In this event’s handler, you must retrieve the index of the selected contact and use it to retrieve the selected item from the ArrayList and display its fields on the other controls. The code of the SelectedIndexChanged event handler is shown in Listing 24.2.
Listing 24.2: Displaying the Fields of the Selected Contact
Private Sub DDListName_SelectedIndexChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles DDListName.SelectedIndexChanged
Response.Write(DDListName.SelectedItem.Value) Dim selIndex As Integer
selIndex = DDListName.SelectedIndex
txtCompany.Text = CType(Contacts(DDListName.SelectedIndex), Contact).Company
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |

1052 Chapter 24 ACCESSING DATA ON THE WEB
txtTitle.Text = CType(Contacts(DDListName.SelectedIndex), Contact).Title radioMarried.Checked = _
CType(Contacts(DDListName.SelectedIndex), Contact).Married
End Sub
The first statement isn’t really required, but I’ve inserted it to show you how to access the selected string on the control. The TextBox and RadioButton controls on the form aren’t bound; we update them from within our code.
The DataBinding project is a simple example, but it demonstrates how to bind a list that resides on the server to a control on a Web form. To better understand how ASP.NET handles data binding, take a look at the code that was transmitted to the client. Press F5 to run the project and, when Internet Explorer appears on your monitor, open the View menu and select Source. In the page’s source code, locate the SELECT control’s tag. This is a plain HTML control that was placed on the page with the following statements:
<SELECT NAME=”DDListName” ID=”DDListName” ONCHANGE=”__doPostBack(‘DDListName’,’’)” LANGUAGE=”javascript” STYLE=”height: 22px; width: 196px; z-index: 101; left: 42px; position: absolute; top: 60px”>
<OPTION VALUE=”0”>Maria Anders</OPTION>
<OPTION VALUE=”1”>Ana Trujillo</OPTION>
<OPTION VALUE=”2”>Thomas Hardy</OPTION>
<OPTION VALUE=”3”>Frédérique Citeaux</OPTION> <OPTION VALUE=”4”>Elizabeth Brown</OPTION>...
Nothing unusual gets transmitted to the client. ASP.NET created a plain, vanilla HTML control and populated it with the names of the contacts. For those who haven’t read the previous chapter, I’ll repeat once again the recurring theme in designing Web applications. On the server’s side, you write an application that’s no different than regular Windows applications. When you execute the application, the compiler gets to work and generates HTML code that will render the Web form you designed as an HTML page, and it connects the events in the browser to event handlers in your application.
Have you noticed another difference between DataBinding and the equivalent Windows application? Don’t you find all the code for updating the TextBox controls on the form a little heavy? In a Windows application, we’d retrieve the SelectedItem, which is an object, cast it to the proper type (the Contact type, in our example), and then call its properties. A statement like the following would be adequate:
txtCompany.Text = CType(DDListName.SelectedItem).Company
That’s because a Windows ListBox (or ComboBox) control can store objects. Once you get a reference to the selected object, you can access all its members directly. But HTML wasn’t designed to handle objects. (Actually, HTML wasn’t even designed to handle applications, and a replacement for HTML is overdue.) That’s why we have to populate the ArrayList at every postback and use the index of the selected item to locate the corresponding element in the ArrayList. These are the differences you must bear in mind as you develop ASP.NET applications. The design process looks and feels like the design process of a Windows application, but it’s not quite the same, because there are fundamental differences in the two environments.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |