Asp. Data binding Overview and the use of data binding expressions in the NET Framework-practical tips

Source: Internet
Author: User
Tags eval string format

<%#%> Grammar

ASP.net introduces a new declarative syntax, <%#%>. This syntax is the basis for using data binding in an. aspx page. All data-binding expressions must be contained in these characters. The following list contains examples of simple data binding from multiple sources:
Simple properties (for the client's syntax):

<%# CustID%>

Collection (Syntax for orders):

<asp:listbox id= "List1" datasource= <%# myarray%> ' runat= ' server ' >

expression (syntax for contact person):

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


Method result (syntax for outstanding balances):

<%# getbalance (CustID)%>


In the previous example, the <%#%> inline tag indicates where the information in a particular data source will be placed in an. aspx page. The following data-binding examples use the TextBox Web server control:

<asp:textbox id=txt text= "<%# custid%>" Runat=server/>


page.databind () versus Control.DataBind ( )

After you determine a specific data source and set an object on an. aspx page, you must bind the data to the data source. You can use the Page.DataBind or Control.DataBind methods to bind data to a data source.

The two methods are used in a similar way. The main difference is that when the Page.DataBind method is invoked, all data sources are bound to their server controls. No data is rendered to the control until the DataBind method of the WEB server control is explicitly invoked or before the page-level Page.DataBind method is invoked. Typically, page.databind (or DataBind) can be invoked from the Page_Load event.

Data-binding expressions Drill down
The data-binding expression is contained within the <%# and%> delimiters and uses the Eval and bind functions. The Eval function is used to define one-way (read-only) bindings. The BIND function is used to define bidirectional (updatable) bindings. In addition to performing data binding by invoking the Eval and bind methods in a data-binding expression, you can also invoke any common scope code within the <%# and%> delimiters to execute the code during page processing and return a value.
When you invoke the DataBind method of a control or Page class, the data-binding expression is parsed. For some controls, such as the GridView, DetailsView, and FormView controls, the data-binding expression is automatically parsed during the control's PreRender event, and no explicit call to the DataBind method is required.
The following code example demonstrates how to use a data-binding expression in conjunction with a FormView control in ItemTemplate.

<asp:formview id= "FormView1" datasourceid= "SqlDataSource1" datakeynames= "ProductID" runat= "Server" > <ite mtemplate> <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& GT;&LT;TD align= ' right ' ><b>quantity per unit:</b></td><td><%# Eval ("QuantityPerUnit" )%></td></tr> <tr><td align= "right" ><b>unit price:</b></td> <td&gt ; <%# Eval ("UnitPrice")%></td></tr> </table> </ItemTemplate> </asp:f

 Ormview>

Using the Eval method
the Eval method computes a late-bound data expression in the template of a data-bound control, such as the GridView, DetailsView, and FormView controls. At run time, the Eval method invokes the Eval method of the DataBinder object, while referencing the current data item of the naming container. A naming container is usually the smallest component of a data-bound control that contains a full record, such as a row in a GridView control. Therefore, you can use the Eval method only for bindings within the template of a data-bound control.
The Eval method returns a string containing the field value from the current record in the data source, taking the name of the data field as an argument. You can supply a second parameter to specify the format of the return string, which is an optional parameter. The string format parameter uses the syntax defined for the format method of the string class.

Using the Bind method
There are some similarities between the Bind method and the Eval method, but there are significant differences. Although you can use the Bind method to retrieve the values of a data-bound field as you would with the Eval method, you use the Bind method when the 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 data source controls. For example, if you have defined SQL Select, Insert, Delete, and Update statements for a data source control, you can make a control from a child control in the template by using the Bind method in the GridView, DetailsView, or FormView control template Extracts values and passes these values to the data source control. The data source control then executes the appropriate database commands. For this reason, you use the BIND function in the EditItemTemplate or insertitemtemplate of a data-bound control.
The Bind method is typically used with an input control, such as a TextBox control rendered by the GridView line in edit mode. When a data-bound control creates these input controls as part of its rendering, the method extracts the input values.
The Bind method uses the name of the data field as a parameter to associate with the bound 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&G
    T
      <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:linkb Utton id= "Cancelupdatebutton" runat= "Server" text= "Cancel" commandname= "Cancel"/> </td> </tr> & Lt;/table>;/edititemtemplate>
 

When you click the Update button for a row, each control property value that is bound with the bind syntax is extracted and passed to the data source control to perform the update operation.

Explicit invocation of the DataBind method
some controls, such as the GridView, FormView, and DetailsView controls, are bound by implicitly calling the DataBind method when they are bound to a data source control through the DataSourceID property. However, there are situations where you need to explicitly invoke the DataBind method to perform the binding.
One of these is when you bind a control to a data source control by using the DataSource property instead of the DataSourceID property. In this case, you need to explicitly call the DataBind method to perform data binding and resolve data-binding expressions.
Another scenario is when you need to manually refresh data in a data-bound control. Suppose you have a page with two controls, both of which display information from the same database (you might use a different view). In this case, you might want to explicitly rebind the control to data to keep the data displayed synchronized. For example, there might be a GridView control that displays a list of products, and a DetailsView control that allows users to edit individual products. Although the GridView and DetailsView controls display data from the same data source, they are bound to different data source controls because the two controls use different queries to get their data. The user may use the DetailsView control to update the record, which causes the update to be performed by the associated data source control. However, because the GridView control is bound to a different data source control, the control will still display the old record value until the page is refreshed. Therefore, after the DetailsView control updates the data, you can call the DataBind method. This causes the GridView control to update its view and to rerun any data-binding expressions and the common scope code within the <%# and%> delimiters. This way, the GridView control will reflect the updates made by the DetailsView control.

use a bind to lookup table
A common scenario for data-bound controls is to allow the user to update or insert the value by selecting a value from the lookup table using the DropDownList control or another list control. In this case, bind the lookup control to a separate data source that returns a list of possible values, and bind the selected value of the lookup control to a field in the parent data-bound row. The
can add this functionality as follows. First, for a lookup control, add a list control (DropDownList or ListBox control) to a template in a data-bound control, such as a GridView, DetailsView, or FormView control. The SelectedValue property of the lookup control is then bound to the related field in the container control's data source. Second, you set the DataSourceID property of the lookup control to a data source control that retrieves the lookup value. Then set the lookup control's DataTextField property to find the field in the table that contains the value you want to display, and set its DataValueField property to the field that finds the unique identifier in the table that contains the lookup value, if applicable.
The following code example shows a DropDownList control that is included in the InsertItemTemplate template of a FormView control (it can also be a Fields property or a GridView control that is included in a DetailsView control The TemplateField insertitemtemplate template in the Columns property of a piece). The SelectedValue property of the DropDownList control uses the Bind method to implement a two-way binding between the CategoryID fields of the current row of the FormView control. Set the DataSourceID property of the DropDownList control to a separate data source control to retrieve a list of possible category names and IDs. Set the DataTextField property of the DropDownList control to look for the CategoryName field in the data source to display a list of possible category names. Set the DataValueField property of the DropDownList control to the CategoryID field that finds the related category name in the data source. When the user selects a category name from the list, the SelectedValue property 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.