Binding Data to Controls - Drop-Down List
(Page 4 of 4 )
Data can also be bounded to the DropDownList control by assigning the column name to the DataTextField property of the DropDownList control in the Page_Load method. This is illustrated in the next example, where we load the last name of customers into a drop-down list when the page is loaded.
Notice that we connect to the database and execute the query in the Page_Load subroutine much as we did in the previous example, with one difference. The database connection is made within an If statement that evaluates the status of the IsPostBack property.
A postback occurs when the page calls itself. A visitor loads a page for the first time by entering the page’s URL into the browser address box or by clicking a hyperlink contained on a different page. This is not a postback. However, once the page is displayed, the page can request itself. This is a postback.

Figure 12-1. The last names shown in the DropDownList control are from the database.
If the page is a postback, then the IsPostBack property is true; otherwise, the IsPostBack property is false. Data connection and data binding occur only when the page isn’t a postback. Therefore, we need to test the value of the IsPostBack property before connecting to the DBMS and binding the data. We do this by reversing the logic of the IsPostBack property. That is, if the IsPostBack property is false (the page is loaded the first time), then we make the condition expression true so that statements within the If statement (connect to the DBMS and bind the data) are executed.
The web page itself is different than the previous example because we created a form that contains the DropDownList. The DropDownList control is populated with the last name of customers from the Customers table (Figure 12-1).
There would be other controls in a real-world application such as a button that when selected causes the selected customer last name to be processed (see Chapter 8).
<%@ 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 cistLastName From
custContact", conCust)
dtrCust = cmdSelectRows.ExecuteReader()
deleteCust.DataSource = dtrCust
deleteCust.DataTextField = "custLastName"
deleteCust.DataBind()
dtrCust.Close()
conCust.Close()
End If
End Sub
</Script>
<html>
<head><title>Drop-Down List Control Data Binding</title></head>
<body>
<form Runat="Server">
<asp:DropDownList ID="deleteCust" Runat="Server" />
</form>
</body>
</html>
Please be sure to check back next week for the conclusion of this article!