Compartir a través de


Data-Binding Expression Syntax

Data-binding syntax allows you to bind control property values to data and specify values for retrieving, updating, deleting, and inserting data.

Data-Binding Syntax

Data-binding expressions are contained within <%# and %> delimiters and use the Eval and Bind functions. The Eval function is used to define one-way (read-only) binding. The Bind function is used for two-way (updatable) binding. In addition to calling Eval and Bind methods to perform data binding in a data-binding expression, you can call any publicly scoped code within the <%# and %> delimiters to execute that code and return a value during page processing.

Data-binding expressions are resolved when the DataBind method of a control or of the Page class is called. For controls such as the GridView, DetailsView, and FormView controls, data-binding expressions are resolved automatically during the control's PreRender event and you are not required to call the DataBind method explicitly.

The following code example shows the use of data-binding expressions with a FormView control in an ItemTemplate.

<asp:FormView ID="FormView1"
  DataSourceID="SqlDataSource1"
  DataKeyNames="ProductID"     
  RunAt="server">
                                    
  <ItemTemplate>
    <table>
      <tr><td align="right"><b>Product ID:</b></td>       <td><%# Eval("ProductID") %></td></tr>
      <tr><td align="right"><b>Product Name:</b></td>     <td><%# Eval("ProductName") %></td></tr>
      <tr><td align="right"><b>Category ID:</b></td>      <td><%# Eval("CategoryID") %></td></tr>
      <tr><td align="right"><b>Quantity Per Unit:</b></td><td><%# Eval("QuantityPerUnit") %></td></tr>
      <tr><td align="right"><b>Unit Price:</b></td>       <td><%# Eval("UnitPrice") %></td></tr>
    </table>                 
  </ItemTemplate>                   
</asp:FormView>
<asp:FormView ID="FormView1"
  DataSourceID="SqlDataSource1"
  DataKeyNames="ProductID"     
  RunAt="server">
                                    
  <ItemTemplate>
    <table>
      <tr><td align="right"><b>Product ID:</b></td>       <td><%# Eval("ProductID") %></td></tr>
      <tr><td align="right"><b>Product Name:</b></td>     <td><%# Eval("ProductName") %></td></tr>
      <tr><td align="right"><b>Category ID:</b></td>      <td><%# Eval("CategoryID") %></td></tr>
      <tr><td align="right"><b>Quantity Per Unit:</b></td><td><%# Eval("QuantityPerUnit") %></td></tr>
      <tr><td align="right"><b>Unit Price:</b></td>       <td><%# Eval("UnitPrice") %></td></tr>
    </table>                 
  </ItemTemplate>                 
</asp:FormView>

Using the Eval Method

The Eval method evaluates late-bound data expressions in the templates of data-bound controls such as the GridView, DetailsView, and FormView controls. At run time, the Eval method calls the Eval method of the DataBinder object, referencing the current data item of the naming container. The naming container is generally the smallest part of the data-bound control that contains a whole record, such as a row in a GridView control. You can therefore use the Eval method only for binding inside templates of a data-bound control.

The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string. The string format parameter uses the syntax defined for the Format method of the String class.

Using the Bind Method

The Bind method has some similarities to the Eval method, but there are significant differences. Although you can retrieve the values of data-bound fields with the Bind method, as you can with the Eval method, the Bind method is also used when data can be modified.

In ASP.NET, data-bound controls such as the GridView, DetailsView, and FormView controls can automatically use the update, delete, and insert operations of a data source control. For example, if you have defined SQL Select, Insert, Delete, and Update statements for your data source control, using Bind in a GridView, DetailsView, or FormView control template enables the control to extract values from child controls in the template and pass them to the data source control. The data source control in turn performs the appropriate command for the database. For this reason, the Bind function is used inside the EditItemTemplate or InsertItemTemplate of a data-bound control.

The Bind method is typically used with input controls such as the TextBox control rendered by a GridView row in edit mode. When the data-bound control creates these input controls as part of its own rendering, it can extract the input values.

The Bind method takes the name of a data field to associate with the bound property, as shown in the following example:

Security noteSecurity Note

This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

<EditItemTemplate>
  <table>
    <tr>
      <td align=right>
        <b>Employee ID:</b>
      </td>
      <td>
        <%# Eval("EmployeeID") %>
      </td>
    </tr>
    <tr>
      <td align=right>
        <b>First Name:</b>
      </td>
      <td>
        <asp:TextBox ID="EditFirstNameTextBox" RunAt="Server"
          Text='<%# Bind("FirstName") %>' />
      </td>
    </tr>
    <tr>
      <td align=right>
        <b>Last Name:</b>
      </td>
      <td>
        <asp:TextBox ID="EditLastNameTextBox" RunAt="Server"
            Text='<%# Bind("LastName") %>'  />
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <asp:LinkButton ID="UpdateButton" RunAt="server"
          Text="Update" CommandName="Update" />
        &nbsp;
        <asp:LinkButton ID="CancelUpdateButton" RunAt="server"
          Text="Cancel" CommandName="Cancel" />
      </td>
    </tr>
  </table>
</EditItemTemplate>

When the Update button for the row is clicked, the values of each control property bound using Bind syntax are extracted and passed to the data source control for the update operation.

Calling the DataBind Method Explicitly

Controls such as GridView, FormView, and DetailsView controls perform binding by calling the DataBind method implicitly when they are bound to a data source control using the DataSourceID property. However, there are situations in which you need to call the DataBind method explicitly.

One situation is if you have bound a control to a data source control using the DataSource property instead of the DataSourceID property. In that case, you need to call the DataBind method explicitly to perform data binding and resolve data-binding expressions.

Another situation is if you need to manually refresh the data in a data-bound control. Consider a page where you have two controls that display information from the same database (perhaps using different views). In that case, you might need to explicitly re-bind the control to data to keep the data display synchronized. For example, you might have a GridView control displaying a list of products and a DetailsView control that allows users to edit an individual product. Although the GridView and DetailsView controls display data from the same source, they are bound to different data source controls because they use different queries to get their data. A user might update a record using the DetailsView control, causing the update to be performed by the associated data source control. However, because the GridView control is bound to a different data source control, it will display old record values until the page is refreshed. Therefore, after the data is updated by the DetailsView control, you can call the DataBind method. This causes the GridView control to update its view as well by re-executing any data-binding expressions and publicly scoped code within the <%# and %> delimiters. As a result, the GridView control reflects the update made by the DetailsView control.

Using Binding for a Lookup Table

A common scenario with data-bound controls is to enable users to update or insert a value by selecting it from a lookup table using a DropDownList control or other list control. In that case, the lookup control is bound to a separate data source that returns the list of possible values, and the lookup control's selected value is bound to a field in the parent data-bound row.

You can add this functionality as follows. First, for the lookup control, you add a list control (a DropDownList or ListBox control) to a template in a data-bound control such as a GridView, DetailsView, or FormView control. You bind the SelectedValue property of the lookup control to the related field in the container control's data source. Then you set the lookup control's DataSourceID property to a data source control that retrieves the lookup values. You set the lookup control's DataTextField property to the field from the lookup table that contains the values to display, and set its DataValueField property to the field from the lookup table that contains the unique identifier for the lookup value, if applicable.

The following code example shows a DropDownList control that is included in the InsertItemTemplate template of a FormView control (this could also be an InsertItemTemplate template of a TemplateField included in the Fields property of a DetailsView control or the Columns property of a GridView control). The SelectedValue property of the DropDownList control uses the Bind method for two-way binding to the CategoryID field of the current row for the FormView control. The DataSourceID property of the DropDownList control is set to a separate data source control that retrieves the list of possible category names and IDs. The DataTextField property of the DropDownList control is set to the CategoryName field from the lookup data source so that a list of possible category names is displayed. The DataValueField property of the DropDownList control is set to the CategoryID field from the lookup data source for the related category name. When a user selects a category name from the list, the SelectedValue property of the DropDownList control is set to the category ID for the selected category name.

<tr>
  <td align="right"><b>Category:</b></td>
  <td><asp:DropDownList ID="InsertCategoryDropDownList" 
                        SelectedValue='<%# Bind("CategoryID") %>' 
                        DataSourceID="CategoriesDataSource"
                        DataTextField="CategoryName"
                        DataValueField="CategoryID"
                        RunAt="Server" />
  </td>
</tr>
<tr>
  <td align="right"><b>Category:</b></td>
  <td><asp:DropDownList ID="InsertCategoryDropDownList" 
                        SelectedValue='<%# Bind("CategoryID") %>' 
                        DataSourceID="CategoriesDataSource"
                        DataTextField="CategoryName"
                        DataValueField="CategoryID"
                        RunAt="Server" />
  </td>
</tr>

The same list control could be used in an edit item template as well.

See Also

Tasks

How to: Bind to Data in a Templated Control

Concepts

Binding to Databases
Binding to Business Objects
Binding to Hierarchical Data
ASP.NET Data Access Overview