HomeASP.NET Learning More About Binding Data to Contro...
Learning More About Binding Data to Controls
Looking for a way to writer fewer lines of code while streamlining your ASP.NET application? This article, the second of two parts, shows you one way to do this. It is excerpted from chapter 12 of ASP.NET 2.0 DeMYSTiFieD, written by Jim Keogh (McGraw-Hill/Osborne; ISBN: 0072261412).
As you learned in Chapter 8, radio buttons are a convenient way to display a group of options from which the visitor selects only one option within the group.
You can store in a table names of radio buttons that are within the same group. This enables you to dynamically define members of the group according to values in the database. For example, a customer might qualify for a unique set of delivery options, as shown by the customer’s profile. The set can be stored in a table.
Data contained in a table is linked to a radio button using the same techniques as are used to link the DropDownList control. For instance, you can assign the column name to the DataTextField property of the radio button control as shown in the next example. For the following example, you’ll need to modify the custContact table to include the DeliveryOption column before running this program.
<%@ 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") cmdSelectRows = New SqlCommand( "Select DeliveryOption From custContact Where Critera='45'", conCust) conCust.Open() dtrCust = cmdSelectRows.ExecuteReader() radioButtonSelection.DataSource = dtrCust radioButtonSelection.DataTextField = "DeliveryOption" radioButtonSelection.DataBind() dtrCust.Close() conCust.Close() End If End Sub </Script> <html> <head><title>Radio Button Control Data Binding </title></head> <body> <form Runat="Server"> <asp:RadioButtonList ID="radioButtonSelection" Runat="Server" /> <p> </form> </body> </html>
Check Box
Check box controls are stored and retrieved identically to how radio buttons are stored and retrieved. The only difference is that you are using a check box instead of a radio box. The next example shows how to create a check box that uses the customer’s last name as its label. Refer to Chapter 8 for more information about how to incorporate a check box control into your application.
<%@ 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") cmdSelectRows = New SqlCommand("Select custLastName From custContact", conCust) conCust.Open() dtrCust = cmdSelectRows.ExecuteReader() checkBoxSelection.DataSource = dtrCust checkBoxSelection.DataTextField = "Customer Last Name" checkBoxSelection.DataBind() dtrCust.Close() conCust.Close() End If End Sub </Script> <html> <head><title>Check Box Control Data Binding</title></head> <body> <form Runat="Server"> <asp:CheckBoxList ID="checkBoxSelection" Runat="Server" /> </form> </body> </html>
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>
A very common practice is to dynamically create hyperlinks on a web page. As you’ll remember from when you learned HTML, a hyperlink consists of at least two attributes. The first is the text or image that appears on the web page, and the second is the URL that is called when the visitor selects the hyperlink.
In the next example, both attributes are stored in a column of a table and are then bound to a Repeater control in the Page_Load subroutine when the web page is loaded.
Let’s modify the Customers table (see Chapter 11) by inserting the following two columns so that we can use those columns in the next example:
CustomerCompany CHAR(30)
CustomerURL CHAR(30)
Statements in the Page_Load subroutine are nearly the same as those you saw earlier in the case of the Repeater control (see the earlier section “The Repeater Control”), except the query returns the CustomerCompany and the CustomerURL from the Customers table.
Statements in the web page are also similar to statements you saw in the web page of the Repeater control, except for the HyperLink control within the ItemTemplate. We assign column names to the Text attribute and to the NavigateURL attribute.
The CustomerCompany column is assigned to the Text attribute, and the CustomerURL column is assigned to NavigateURL. This is called when the visitor selects the hyperlink.
<%@ 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") cmdSelectRows = New SqlCommand( "Select CustomerCompany, CustomerURL From Customers", conCust) conCust.Open() dtrCust = cmdSelectRows.ExecuteReader() hyperLinks.DataSource = dtrCust hyperLinks.DataBind() dtrCust.Close() conCust.Close() End If End Sub </Script> <html> <head><title>Hyperlink Data Binding</title></head> <body> <form Runat="Server"> <asp:Repeater ID="hyperLinks" Runat="Server"> <ItemTemplate> <ASP:HyperLink Text='<%# Container.DataItem("CustomerCompany") %>' NavigateURL='<%# Container.DataItem("CustomerURL") %>' Runat="Server" /> </ItemTemplate> </asp:Repeater> </form> </body> </html>
The line <td><%# Container.DataItem(“CustomerFirstName”) %></td> inserts data from the CustomerFirstName column into a column of a table on the web form
a. True
b. False
If IsPostBack is true, then
a. The web page is loaded for the first time.
b. The web page called itself.
c. The web page sent data to the database.
d. None of the above.
The AlternatingItemTemplate
a. Defines the format for all items that appear in the Repeater control.
b. Defines the format for first item that appears in the Repeater control.
c. Defines the format for alternating items that appear in the Repeater control.
d. Defines the format for alternating items that appear in the list box control.
DataBind()
a. Removes a data binding from a control.
b. Binds data to a DBMS.
c. Binds data to a database.
d. Binds data to a control.
Data binding most commonly occurs in the
a. OnClick() method
b. MouseOver() event
c. Page_Load event
d. None of the above
Data for data binding can come from
a. A database
b. An expression
c. A property of another control
d. All of the above
Calculated results from a database cannot be bound to a list box control.
a. True
b. False
The Repeater control is visible on the web page.
a. True
b. False
Separator-Template: Used to separate data displayed by the Repeater control.
a. True
b. False
Data binding is restricted to data that the user ID is authorized to retrieve.
a. True
b. False
Answers
a. True
b. The web page called itself.
c. Defines the format for alternating items that appear in the Repeater control.
d. Binds data to a control.
c. Page_Load event
d. All of the above
b. False
b. False. The control itself is not visible. On the other hand, the data output by the control is visible.
a. True
a. True. The success or failure of any attempt to retrieve data depends on having the necessary permissions.