Learning More About Binding Data to Controls - List Box
(Page 2 of 4 )
The List Box control is bound to data much as you bind data to the drop-down list box, which you learned how to do earlier in this chapter. The actions of connecting to the database, sending the query, and binding data occur within the Page_Load subroutine. Statements required to execute these tasks should be enclosed within an If statement that executes if the IsPostBack property is false, which means that the page is being loaded for the first time (see the earlier section “Drop-Down List”).
The following example illustrates how to bind data to a list box control. In this example we’re populating the list box with the CustomerLastName column from the Customers table. Notice that once again the column name is used in the Page_Load subroutine to bind the custLastName to the DataTextField property of the list box.
The web page consists of a form that contains the list box control. Only the list box control is used in this example (Figure 12-2). You can insert other controls (see Chapter 8) after you are comfortable binding data to the list box.

Figure 12-2. The list box contains last names from the database.
<%@ Import Namespace="System.Data.SqlClient" %>
<Script Runat="Server">
Sub Page_Load
If Not IsPostBack Then
Dim conCust As SqlConnection
Dim cmdSelectRows As SqlCommand
Dim dtrCust As SqlDataReader
conCust = New SqlConnection( "Server=localhost;UID=
MyID;PWD=MyPassword;Database=CustomerContact Data")
conCust.Open()
cmdSelectRows = New SqlCommand("Select custLastName From
custContact", conCust)
dtrCust = cmdSelectRows.ExecuteReader()
lstCustomerLastName.DataSource = dtrCust
lstCustomerLastName.DataTextField = "custLastName"
lstCustomerLastName.DataBind()
dtrCust.Close()
conCust.Close()
End If
End Sub
</Script>
<html>
<head><title>List Box Control Data Binding</title></head>
<body>
<form Runat="Server">
<asp:ListBox ID="lstCustomerLastName" Runat="Server" />
</form>
</body>
</html>
Next: Hyperlinks >>
More ASP.NET Articles
More By McGraw-Hill/Osborne
|
This article is excerpted from chapter 12 of ASP.NET 2.0 DeMYSTiFieD, written by Jim Keogh (McGraw-Hill/Osborne; ISBN: 0072261412). Check it out today at your favorite bookstore. Buy this book now.
|
|