DekGenius.com
[ Team LiB ] Previous Section Next Section

7.3 Data Binding

Although Examples Example 7-1 and Example 7-2 are written in different languages and use different techniques for retrieving data, they both write out the rendering code for formatting the data manually. In simple examples like these, this does not seem too burdensome. When doing more complex rendering, though, it can become quite involved and produce code that is difficult to maintain.

When working with data in a rich client application, the solution has been to use data-bound controls to display data, allowing the controls to take care of the rendering of each row of data based on control properties set by the developer. Microsoft introduced a similar idea for web development by adding client-side data-binding features to Internet Explorer. However, these features were only useful when you could be certain that all of your clients were using Internet Explorer, and in some cases, their use entailed expensive marshalling of data to the client.

ASP.NET introduces a new server-side data-binding feature that addresses these issues. Data binding to server controls in ASP.NET can significantly reduce the amount of code that needs to be written and maintained for displaying data. In addition, since all data binding occurs on the server side and only HTML is returned to the client, server-side data binding provides great cross-browser compatibility.

You can perform data binding against properties for single-value binding or against data sources that contain multiple rows, such as collections, data tables, and data views, allowing rich formatting of data with a minimum of code. Data binding can be performed explicitly by using the <%# %> syntax, or implicitly by setting the data source of a bindable control to an appropriate object (objects to be bound to must implement the IEnumerable interface). In both cases, the data binding occurs when the Databind method of the page or control is called. Note that when Databind is called at the page level, the Page class will, in turn, call Databind on all of its constituent controls. Therefore, if you have a large number of controls on a page, only a few of which are databound, it may be more efficient to call the Databind method of these controls directly.

7.3.1 Binding to Properties

Example 7-3, one of the simplest possible implementations of data binding, binds to a property exposed at the page level. In this example, we create a public member variable called FontColor, and in the Page_ Load event handler, we set its value to "Red". In the body of the page, we use the <%# %> syntax to tell ASP.NET to evaluate the contents of these brackets when the DataBind method of the page is called. Back in Page_ Load, we call DataBind, which substitutes the value of the FontColor property for the two data binding expressions in the body. The output of Example 7-3 is shown in Figure 7-3. Example 7-4 shows the HTML produced by Example 7-3.

Example 7-3. BindProperty.aspx
<%@ Page Language="VB" %>
<html>
<head>
   <title>Simple DataBinding Example</title>
   <script runat="server">
      Dim FontColor As String
      Sub Page_Load( )
         FontColor = "Red"
         DataBind( )
      End Sub
   </script>
</head>
<body>
   <h1>Simple DataBinding Example</h1>
   The value for FontColor is 
      <font color="<%# FontColor %>"><%# FontColor %></font>.
</body>
</html>
Figure 7-3. Output of BindProperty.aspx
figs/anet2_0703.gif
Example 7-4. HTML Output of BindProperty.aspx
<html>
<head>
   <title>Simple DataBinding Example</title>
</head>
<body>
   <h1>Simple DataBinding Example</h1>
   The value for FontColor is 
      <font color="Red">Red</font>.
</body>
</html>

7.3.2 Binding to Collections

While more involved than binding to a property, binding to a collection is still quite simple. Example 7-5 uses an ArrayList to store values that will be bound to an ASP.NET DropDownList control. The DropDownList control and a Label control for output are declared in the body of the page. Setting the autopostback attribute of the DropDownList control to True results in the page being posted back to the server any time the selection in the dropdown is changed. In the Page_Load event handler, if the page request is not the result of a postback, we declare a new ArrayList and add three items to it. Next, we set the DataSource property of the DropDownList control to be the ArrayList, call the page's DataBind method (which calls DataBind on its children), and then set the initial selection of the DropDownList to the first item.

Whether or not the request is the result of a postback, we then set the output text via the Label's Text property and set the foreground color of the Label control based on the value of the selected item in the dropdown. Note that because the ForeColor property is of type System.Drawing.Color, the example uses the FromName method exposed by the Color class to translate the string containing the color name to an appropriate instance of the Color class. The output of Example 7-5 is shown in Figure 7-4.

Example 7-5. BindCollection.aspx
<%@ Page Language="VB" %>
<html>
<head>
   <title>Collection DataBinding Example</title>
   <script runat="server">
      Dim FontColor As String
      Sub Page_Load( )
         If Not IsPostBack Then
            Dim Colors As New ArrayList( )
            Colors.Add("Red")
            Colors.Add("Green")
            Colors.Add("Blue")
            Color.DataSource = Colors
            DataBind( )
            Color.SelectedIndex = 0
         End If
         Output.Text = "The value for FontColor is " & _
            Color.SelectedItem.Value & "."
         Output.ForeColor = _
            System.Drawing.Color.FromName(Color.SelectedItem.Value)
         End Sub
    </script>
</head>
<body>
   <h1>Collection DataBinding Example</h1>
   <form runat="server">
      Choose a color from the list for the font color:
      <asp:dropdownlist id="Color" autopostback="True" runat="server"/>
      <br/>
      <asp:label id="Output" runat="server"/>
   </form>
</body>
</html>
Figure 7-4. Output of BindCollection.aspx
figs/anet2_0704.gif

7.3.3 Binding to DataViews

Binding to richer data sources, such as DataTables and DataViews, is even more powerful than binding to collections, though still relatively simple. The DataView class provides a representation of the data in a DataTable that can be sorted and filtered, and also implements the necessary interfaces that allow it to be databound. These data sources can be used by:

  • Retrieving data in a dataset and binding to the constituent DataTables

  • Building DataViews, based on the data in the data table, or retrieving the table's DefaultView property, which returns an unsorted, unfiltered DataView

  • Creating DataTables and/or DataViews programmatically

Binding a DataTable or DataView to controls such as DataGrid, DataList, and Repeater provides an extremely powerful technique for displaying and editing data with a minimum of code. It also provides substantial flexibility in how the data is formatted and displayed.

The examples in Section 7.4 and Section 7.5 demonstrate how to bind the default DataView of a table to a DataGrid for display.

    [ Team LiB ] Previous Section Next Section