Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
136
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

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