What Does This Book Cover?

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.

    note

    You cannot directly bind XML documents unless you load their contents in one of the classes mentioned in the preceding bulleted list. You can bind XML documents in two ways. You can load the XML document into a DataSet object and then bind the DataSet object. Alternatively, you can parse the XML document with an XML reader class and bind the collection of nodes you obtain.

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" css 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.

Table 1-1 ASP.NET Iterative Controls

Control

Description

Repeater

Creates a custom layout for displaying the control s contents by repeating a specified template for each item in the bound list. You define an ASP.NET template for various categories of items (header, footer, item, separator, and so forth), and the control applies it repeatedly in the page.

The Repeater control has no built-in layout, so you must explicitly declare all ASP.NET formatting and style tags.

DataList

Displays the contents of a data bound list through ASP.NET templates. The DataList control supports selecting and editing. The appearance of the DataList control may be customized to some extent by setting style properties for different parts of the control. Compared to the Repeater control, DataList shows off predefined layouts, more advanced formatting capabilities, plus support for selecting and editing.

DataGrid

The DataGrid control renders a multi-column, data bound grid of data. It allows you to define various types of columns and control the layout of the resulting cells through predefined layouts and ASP.NET templates. You can also add specific functionality such as edit button columns and link columns. The DataGrid control also supports a variety of options for paging through data.

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.



Building Web Solutions with ASP. NET and ADO. NET
Building Web Solutions with ASP.Net and ADO.NET
ISBN: 0735615780
EAN: 2147483647
Year: 2002
Pages: 75
Authors: Dino Esposito

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