Databinding and List Controls

I l @ ve RuBoard

Up to this point, we've introduced all four types of ASP.NET list controls and you learned how to manipulate each programmatically. In the next section, you'll learn how to automatically create the items in a list from an external data source and bind a list selection to that data source. Before we begin, let's take a quick look back at how we would databind list controls in previous versions of ASP.

For all its strengths, there are some aspects of previous versions of ASP that are just plain awkward . Take the code in Listing 6.12, for instance.

Listing 6.12 Databinding <select> tag in previous versions of ASP.
 <SELECT NAME="STATUS">     <OPTION VALUE="PENDING"         <%If rs("Status") = "PENDING" Then Response.Write "selected"%>>         PENDING     </OPTION>     <OPTION        VALUE="ACTIVE"        <%If rs("Status") = "ACTIVE" Then Response.Write "selected"%>>             ACTIVE     </OPTION>     <OPTION         VALUE="INACTIVE"         <%If rs("Status") = "INACTIVE" Then Response.Write "selected"%>>             INACTIVE     </OPTION> </SELECT> 

This example illustrates how, in previous versions of ASP, a task as simple as binding the value of a <select> tag to a recordset column required a great deal of inline script. You've probably been frustrated when your favorite development environment complained when you included server-side script within a <select> tag.

Creating the items in a list control from a datasource was equally awkward, as shown in Listing 6.13.

Listing 6.13 Databinding <options> in a <select> tag in previous versions of ASP.
 <SELECT NAME="STATUS">     <%Do While Not rs.EOF%>         <OPTION VALUE="<%rs(0)%>"><%=rs(1)%></OPTION>     <%rs.MoveNext       Loop%> </SELECT> 

Why do I reminisce like this? Only to make you fully appreciate the simplicity you're about to see. Databinding the list of items in ASP.NET list controls is as easy as

  • Creating or obtaining your datasource

  • Setting the DataSource property of the list control

  • Calling the DataBind method of the list control or Page object

Listing 6.14 creates a data source of cities in Texas and binds a DropDownList control to it. Figure 6.6 shows the databinding in action.

Figure 6.6. The output from the code in Listing 6.14.

Listing 6.14 Databinding the items in a DropDownList control (6databind01.aspx).
 <%@ Page language="vb"%> <html> <head>     <script language="VB" runat="server">         Sub Page_Load(sender As Object, e As EventArgs)             Dim Cities as ArrayList = new ArrayList()             Cities.Add ("Houston")             Cities.Add ("Dallas")             Cities.Add ("Austin")             Cities.Add ("San Antonio")             Cities.Add ("South Padre Island")             CityList.DataSource = Cities             CityList.DataBind()         End Sub     </script> </head> <body>     <form runat="server">         <h3>Databinding list controls</h3>         <asp:DropDownList id="CityList" runat="server"/>     </form> </body> </html> 

In this example, we created the data source (in this case an array of cities in Texas), set the DataSource property of the list control equal to this array, and finally called the DataBind method of the control to populate the list. That's all there is to it! Keep in mind that the data source could just as easily have been some XML data or an ADO.NET data source. Just to prove it, we'll do that in the next example.

Using DataTextField and DataValueField Properties

In the previous example, both the value and the text of the list items were the same. However, in many instances we need to display some friendly text to the user while keeping some unique ID for the list item value.

Listing 6.15 illustrates an example that displays a list of products from the Northwind database in Microsoft SQL Server, and Figure 6.7 shows the output.

Figure 6.7. The output from the code in Listing 6.15.

Listing 6.15 Specifying the Text and Value fields when databinding a DropDownList control (6databind03.aspx).
 <%@ Page language="vb"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SqlClient"%> <html> <head> <script language="VB" runat="server">     Sub Page_Load(sender As Object, e As EventArgs)         If Not IsPostBack Then             'Declare our SQL Statement             Dim cmd As String = "SELECT ProductID, ProductName FROM Products"             'Create our ADO SQL Adapter             Dim DSAdapter As SqlDataAdapter             DSAdapter = New SqlDataAdapter(cmd, _                 "server=localhost;uid=sa;pwd=;database=Northwind")             'Create the DataSet             Dim ProductsData As DataSet = New DataSet()             'Fill the DataSet             DSAdapter.Fill(ProductsData, "Products")             ProductsList.DataSource = ProductsData.Tables("Products").DefaultView             'Set the column to supply the list item value             ProductsList.DataValueField = "ProductID"             'Set the column to supply the list item text             ProductsList.DataTextField = "ProductName"             ProductsList.DataBind()         End If     End Sub     Sub ProductsList_Change(Sender as Object, e as EventArgs)         ProductSelection.Text = "You've selected Product #:" _             & ProductsList.SelectedItem.Value     End Sub </script> </head> <body> <form runat="server"> <h3>Using DataTextField and DataValueField</h3>     Please select a product below:<br>     <asp:DropDownList         id="ProductsList"         runat="server"         onselectedindexchanged="ProductsList_Change"         autopostback="True"/>     <asp:label id="ProductSelection" runat="Server" /> </form> </body> </html> 

In this example, we display values from the ProductName database column while setting the value for the list item equal to the ProductID column. Although this kind of databinding is pretty powerful, it's only half the story.

Databinding List Control Selections

As you learned in previous chapters, ADO.NET also lets you bind the values of your Web controls to data elsewhere on your Web form. Consider the example shown in Listing 6.16 (Figure 6.8 shows the output).

Figure 6.8. The output from the code in Listing 6.16.

Listing 6.16 Databinding the selection in a DropDownList control (6databind02.aspx).
 <%@ Page language="vb"%> <html> <head> <script language="VB" runat="server">     Sub Page_Load(sender As Object, e As EventArgs)         If Not IsPostBack Then             Dim Cities as ArrayList = new ArrayList()             Cities.Add ("Houston")             Cities.Add ("Dallas")             Cities.Add ("Austin")             Cities.Add ("San Antonio")             Cities.Add ("South Padre Island")             CityList.DataSource = Cities             CityList.DataBind()             CityButtons.DataSource = Cities             CityButtons.DataBind()         End If         Page.DataBind()     End Sub </script> </head> <body> <form runat="server">     <h3>Databinding list control selections</h3>     Please select a city below:<br>     <asp:radiobuttonlist id="CityButtons" runat="Server"         onselectedindexchanged="CityButtons_SelectedIndexChanged"         autopostback="True"/>     You've selected:<br>     <asp:DropDownList id="CityList" runat="server"         SelectedIndex="<%# CityButtons.SelectedIndex%>"/> </form> </body> </html> 

We have added an additional list control to the form, this time a RadioButtonList . Just as before, we've bound each control to the CityList array to create the list items. Note that this time we've wrapped this code block inside an If...Then block, evaluating the IsPostBack property of the page. We do this so that the list items are created only the first time the page loads.

The idea is to change the selection in the drop-down list based on the selection in the first list, much as we did early in the chapter. You'll probably notice that this example required much less code. This is because of the new databinding features in ASP.NET Web controls that allow us to bind properties of our controls to external data sources. To bind the selection of the control in this case, we simply use the databinding syntax you learned in Chapter 3 to bind the SelectedIndex property of the DropDownList control to the same property in the RadioButtonList control. We then set the AutoPostBack property equal to True for the radio list so that we post back to the server whenever the selection changes. The actual databinding takes place with the last line of the Page_Load event handler with the call to Page.Databind() . We could just as easily have called the DataBind() methods of each control individually, but calling Page.DataBind() saves a great deal of code, especially when your Web forms become quite large.

I l @ ve RuBoard


Asp. Net. By Example
ASP.NET by Example
ISBN: 0789725622
EAN: 2147483647
Year: 2001
Pages: 154

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net