ASP.NET Data Binding

ASP.NET Data Binding

Data binding is the process of retrieving data from a source and dynamically associating it to a property of a visual element. Depending on the context in which the element will be displayed, you can map the element to either an HTML tag or a .NET Web control.

In ASP.NET, the atomic elements that work together to generate page output are the Web controls. In ASP.NET data binding, the application retrieves data from any .NET-compliant data source and then allows you to selectively manipulate and assign this data to properties of controls that have been specially designed to support data binding. These controls are known as data bound controls. ASP.NET Web server controls can be bound to a data source by using a heterogeneous bunch of properties, including Text, DataSource, and DataTextField. Later in the chapter, you’ll see how to handle binding by using a combination of these and other control-specific properties.

The DataSource property in particular lets you specify the data source object to which the control is linked. Notice that this link is logical and does not result in any underlying operation until you explicitly call another method. Not all properties in a Web control programming interface can be data bound. You activate data binding on a control by calling the method DataBind. When this method executes, the control loads data from the associated data source, evaluates the data bound properties, and redraws its user interface to reflect changes.

Feasible Data-Binding Sources

Many .NET classes can be used as data sources—not just those dealing with database contents. In general, any object that exposes the ICollection interface is a potential source of data binding. The ICollection interface defines size, enumerators, and synchronization methods for all .NET collections. As a result, you can bind a Web control to any of the following data structures:

  • In-memory .NET collection classes including arrays, dictionaries, sorted and linked lists, hash tables, stacks, and queues.

  • User-defined data structures, as long as the structure exposes ICollection or one of the interfaces based on it (such as IList).

  • Database-oriented classes such as DataTable and DataSet. Bear in mind that in general a DataSet object can contain multiple tables. In this case, you would assign the DataSet object to the DataSource property and assign the name of the selected DataTable object to the control’s DataMember property.

  • Filtered views built on top of DataTable objects that show only a subset of the contained rows. Views are represented by a DataView class or any class that you have built from a DataTable object.

Simple Data Binding

In ASP.NET, simple data binding is a connection between one piece of data and a server control property. This connection is established through a special expression that is evaluated when the code in the page being processed calls the DataBind method either on the Page object or on the control.

A data-binding expression is any text enclosed in angle brackets and percent signs (<%…%>) and prefixed by the number symbol (#). You can include a data-binding expression as the value of an attribute in the opening tag of a server control or anywhere else on the page. You cannot programmatically assign a data-binding expression to a property of a Web control. If the data-binding expression contains quotation marks, use a single quotation mark (') to wrap the whole expression, as shown here:

theLabel.Text='<%# "Hello, world" %>';

Within the delimiters, you can invoke user-defined page methods, static methods and properties, and methods of any other page components. The following code shows a label control whose Text property is bound to the name of the currently selected element in a drop-down list control:

<asp:label runat="server" Text='<%# dropdown.SelectedItem.Text %>' />

The data-binding expression can accept a minimal set of operators, mostly for concatenating subexpressions. When you need more advanced processing and are using external arguments, resort to a user-defined method. The only requirement for a user-defined method is to be callable within the page. When you plan to use code that is not resident in the .ASPX page (for example, if you use code-behind techniques), make sure the method is declared public or protected.

Let’s walk through an example that illustrates how to arrange a form-based record viewer by using simple data binding with text boxes. (The full source code for the FormViewer.aspx application is available on the companion CD.) The user interface supplies three text boxes, one for each of the retrieved fields. The data source is the Employees table of the Northwind database in SQL Server 2000. The query selects three fields: employeeid, firstname, and lastname. The binding takes place between the text boxes and the fields. Only one record at a time is displayed; the user clicks the Previous and Next buttons to move through the data. You can see what the application looks like in Figure 1-1.

Figure 1-1
The text boxes are bound to fields in the Employees table from the SQL Server 2000 Northwind sample database.

The binding expression employs a user-defined method named GetBoundData.

<asp:textbox runat="server" id="txtID" cssclass="StdTextBox" 
    Text = '<%# GetBoundData("employeeid") %>' />

GetBoundData takes the name of the field to display and retrieves the position of the current record from the ASP.NET Session object. It then retrieves the value and passes it to the ASP.NET run time for actual rendering.

public String GetBoundData(String fieldName)
    DataSet ds = (DataSet) Session["MyData"];
    DataTable dt = ds.Tables["EmpTable"];
    int nRowPos = (int) Session["CurrentRecord"];

    String buf = dt.Rows[nRowPos][fieldName].ToString();
    return buf;
Complex Data Binding

Complex data binding occurs when you bind a list control or an iterative control to one or more columns of data. List controls comprise DropDownList, CheckBoxList, RadioButtonList, and ListBox. Iterative controls are Repeater, DataList, and DataGrid. The characteristics of ASP.NET iterative controls are briefly summarized in Table 1-1.

List controls have a more complex and versatile user interface than labels and text boxes. Because a list control handles (or at least has in memory) more items simultaneously than a label or a text box, you should associate the list control explicitly with a collection of data—that is, the data source. Depending on its expected behavior, a list control will select the needed items from memory and properly format and display them.

Iterative controls take a data source, loop through its items, and apply HTML templates to its rows. This basic behavior is common to all three ASP.NET iterative controls. The controls differ in their layout capabilities and the functionality they support.

Let’s see how complex forms of data binding apply to key Web controls.