Use of the Data Binding summary and data binding expression in the ASP. NET Framework, asp.net Summary

Source: Internet
Author: User

Use of the Data Binding summary and data binding expression in the ASP. NET Framework, asp.net Summary

<% # %> Syntax

ASP. NET introduces a new declarative syntax <% # %>. This syntax is used to bind data on the. aspx page. All data binding expressions must be included in these characters. The following list contains examples of simple data binding from multiple sources:
Simple attributes (for the customer's syntax ):

<%# custID %>

Set (Order syntax ):

<asp:ListBox id="List1" datasource='<%# myArray %>' runat="server">

Expression (for the contact syntax ):

<%# ( customer.First Name + " " + customer.LastName ) %>


Method Result (syntax for unsettled balances ):

<%# GetBalance(custID) %>


In the previous example, <% # %> inline markup is used to indicate where information from a specific data source will be placed on the. aspx page. The following data binding example uses the TextBox Web Server Control:

<asp:textbox id=txt text="<%# custID %>" runat=server />


Page. DataBind () versus Control. DataBind ()

After you have determined the specific data source and set the objects on the. aspx page, you must bind the data to the data source. You can use the Page. DataBind or Control. DataBind method to bind data to the data source.

These two methods are used in a similar way. The main difference is that after the Page. DataBind method is called, all data sources are bound to their server controls. No data is presented to the control before the DataBind method of the Web server control is explicitly called or the Page-level Page. DataBind method is called. Generally, you can call Page. DataBind (or DataBind) from the Page_Load event ).

In-Depth Data Binding expression
The data binding expression is included in the <% # And %> delimiters and uses the Eval and Bind functions. The Eval function is used to define one-way (read-only) binding. The Bind function is used to define bidirectional (updatable) binding. In addition to calling the Eval and Bind methods in the data binding expression to perform data binding, you can also call any common code within the <% # And %> delimiters, to execute the code During page processing and return a value.
When the DataBind method of the control or Page class is called, the data binding expression is parsed. Some controls, such as the GridView, DetailsView, and FormView controls, automatically parse the data binding expression during the PreRender event of the control and do not need to explicitly call the DataBind method.
The following code example demonstrates how to use a data binding expression with the FormView control in 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>

Use the Eval Method
The Eval method can calculate the post-bound data expression in the template of a data binding control (such as the GridView, DetailsView, and FormView controls. At runtime, the Eval method calls the Eval method of the DataBinder object and references the current data item of the named container. A naming container is usually the smallest component of a data binding control that contains a complete record, such as a row in the GridView control. Therefore, the Eval method can only be used for binding to the template of the data binding control.
The Eval method uses the name of a data field as a parameter and returns a string containing the value of this field from the current record of the data source. The second parameter can be provided to specify the format of the returned string. this parameter is optional. String Format parameters are defined using the Format method of the String class.

Bind Method
The Bind method has some similarities with the Eval method, but there are also great differences. Although the Bind method can be used to retrieve the value of a Data Binding field like the Eval method, the Bind method must be used when the data can be modified.
In ASP. NET, data binding controls (such as the GridView, DetailsView, and FormView controls) can automatically use the update, delete, and insert operations of data source controls. For example, if you have defined SQL Select, Insert, Delete, and Update statements for the data source control, you can use the Bind method in the GridView, DetailsView, or FormView control template, the control can extract values from the Child control in the template and pass these values to the data source control. The data source control then executes appropriate database commands. For this reason, Bind functions must be used in EditItemTemplate or InsertItemTemplate of the data binding control.
The Bind method is usually used with the input control, for example, the TextBox Control rendered by the row of the GridView in editing mode. When the data binding control creates these input controls as a part of its own rendering, this method can extract the input value.
The Bind method uses the name of the data field as the parameter to associate with the binding property, as shown in the following example:

<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" />         <asp:LinkButton ID="CancelUpdateButton" RunAt="server"     Text="Cancel" CommandName="Cancel" />   </td>  </tr> </table></EditItemTemplate>

When you click the Update button of a row, the attribute values of each control bound with the Bind syntax are extracted and passed to the data source control for Update.

Explicitly call the DataBind Method
Some controls, such as the GridView, FormView, and DetailsView controls, are bound to the data source control through the performanceid attribute by implicitly calling the DataBind method. However, in some cases, you need to explicitly call the DataBind method to perform binding.
One of the cases is when a control is bound to the data source control using the DataSource property instead of the performanceid property. In this case, you need to explicitly call the DataBind method to execute the data binding and parsing data binding expressions.
Another scenario is when you need to manually refresh the data in the data binding control. Suppose there is such a page with two controls, both of which display information from the same database (different views may be used ). In this case, you may need to explicitly rebind the control to the data to keep the data display synchronized. For example, you may have a GridView control that displays the product list and a DetailsView control that allows you to edit a single product. Although the data displayed by the GridView and DetailsView controls come from the same data source, they are bound to different data source controls because they use different queries to obtain their data. The user may use the DetailsView control to update records, causing the associated data source control to execute updates. However, because the GridView control is bound to different data source controls, the control will still display the old record value until the page is refreshed. Therefore, after the DetailsView control updates data, you can call the DataBind method. This causes the GridView control to update its view and re-execute any data binding expression and the Public scope code within the separators <% # And %>. In this way, the GridView control will reflect the updates made by the DetailsView control.

Bind a query table
A common solution for data binding controls is to allow users to use the DropDownList control or other list controls to select a value from the lookup table to update or insert this value. In this case, bind the query control to a separate data source that returns the list of possible values, and bind the selected value of the query control to the field in the parent data binding row.
You can add this function as follows. First, add a list control (DropDownList or ListBox control) to a template bound to the Data Control (such as the GridView, DetailsView, or FormView control ). Then, bind the SelectedValue attribute of the query control to the relevant fields in the data source of the Container Control. Second, set the performanceid attribute of the search control to a data source control that can retrieve the search value. Set the DataTextField attribute of the query control to the field containing the value to be displayed in the query table, set its DataValueField attribute to the field containing the unique identifier of the search value in the query table (if applicable ).
The following code example demonstrates a DropDownList control, this control is included in the InsertItemTemplate template of the FormView control (it can also be included in the Fields attribute of the DetailsView control or the InsertItemTemplate template of the TemplateField in the Columns attribute of the GridView control ). The SelectedValue attribute of the DropDownList control uses the Bind method to implement bidirectional binding with the CategoryID field of the current row of the FormView control. Set the performanceid attribute of the DropDownList control to a separate data source control to retrieve the list of possible category names and IDs. Set the dropextfield attribute of the DropDownList control to the CategoryName field in the data source to display the list of possible category names. Set the DataValueField attribute of the DropDownList control to the CategoryID field of the category name in the data source. When you select a category name from the list, the SelectedValue attribute of the DropDownList control is set to the category ID of the selected category name.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.