asp.net 2.0 data binding syntax for advanced data processing

Source: Internet
Author: User
Tags bind contains count eval expression integer net tostring
Asp.net| Advanced | data | syntax is discussed in the previous "data Binding in Templates" section, ASP. NET contains a declarative data-binding syntax for associating a data source field with a control's properties in a data-binding template. You can also use <%# in your code ... > syntax to perform data binding of arbitrary values, such as page and control properties, collections, expressions, and even the return result of a method call. To force the calculation of data binding values, you must call the DataBind method on the page or control that contains the data binding syntax. The following table shows some examples of data-binding syntax in asp.net.

Single Property Customer: <%# CustID%>
Set Orders
Expression Contact <%# (Customer. FirstName + "" + customer. LastName)%>
The return value of the method Outstanding Balance: <%# getbalance (CustID)%>
  
Although the above syntax looks similar to the ASP's Response.Write convenient syntax (<%=%>), their behavior is decidedly different. ASP Response.Write Convenient syntax calculates values when the page is processed, and the ASP.net data binding syntax evaluates values only when the DataBind method is invoked.

DataBind is a way to page and all control of a service. When you call the DataBind of the parent control, it calls the DataBind method of all child controls in turn. For example, Datalist1.databind () invokes the DataBind method of all controls in the DataList template. Calling the page's DataBind method--page.databind () or simply calling DataBind ()--causes all data-binding expressions on the page to be evaluated. The DataBind method is usually invoked only in the Page_Load event of the page, as shown in the following example.
In any declarative fragment of an. aspx page, you can use the binding syntax and specify the data type that the runtime expects for its valuation. The simple attributes, expressions, and methods shown in the previous example display text content to the user when they are computed. In this case, the value of the data-binding expression is of type string. In the example set above, the type of the value of the data binding syntax is the DataSource property of the listbox. You will find that the type of the cast value in the binding expression is necessary to generate the desired result. For example, if Count is an integer:

Number of Records: <%# count. ToString ()%>
Asp. NET data binding syntax supports the binding of properties of public variables, page properties, and other controls on a page. The following example shows how to bind to a common variable and a simple property of a page. Note that these values have already been initialized before DataBind () is invoked.

<script language= "VB" runat= "Server"
Sub Page_Load (sender as Object, E as EventArgs)
Page.DataBind
End Sub

ReadOnly Property CustID () as String
Get
Return "ALFKI"
End Get
End Property

ReadOnly Property OrderCount () as Integer
Get
Return 11
End Get
End Property
</script>
<form action= "databind1_vb.aspx" runat= "Server"
Customer: <b> <%# custid%> </b> <BR/>
Open Orders: <b> <%# ordercount%> </b>
</form>
The following example shows how to bind to a property of another control:

<asp:dropdownlist id= "statelist" runat= "Server"
<asp:ListItem> CA </asp:ListItem>
......
</asp:DropDownList>

<asp:button id= "Button1" text= "Submit" runat= "Server"/>
Selected state: <asp:label id= "Label1" text= ' <%# StateList.SelectedItem.Text '%> ' runat= ' server '/>

server controls of the list type (such as DropDownList, ListBox, and HtmlSelect) use the collection as the data source. The following example shows how to bind to a common language runtime collection type. These controls can only be bound to a collection that supports IEnumerable, ICollection, or IListSource interfaces. More commonly, it can be bound to ArrayList, Hashtable, DataView, and DataReader. The following example shows how to bind to a ArrayList.

Sub Page_Load (sender as Object, E as EventArgs)
If not IsPostBack Then
Dim values as arraylist= new ArrayList ()
Values. ADD ("in")
Values. ADD ("KS")
Values. ADD ("MD")
Values. ADD ("MI")
Values. ADD ("OR")
Values. ADD ("TN")

Dropdown1.datasource = values
Dropdown1.databind
End If
End Sub
The following example shows how to bind to a DataView. Please note that the DataView class is defined in the System.Data namespace.

Sub Page_Load (sender as Object, E as EventArgs)
If not IsPostBack Then
Dim DT as DataTable
Dim Dr as DataRow
Dim I as Integer

' Setting up a DataTable
DT = New DataTable
Dt. Columns.Add (New DataColumn ("IntegerValue", GetType (Integer))
Dt. Columns.Add (New DataColumn ("StringValue", GetType (String))
Dt. Columns.Add (New DataColumn ("Datetimevalue", GetType (DateTime))
Dt. Columns.Add (New DataColumn ("Booleanvalue", GetType (Boolean))

' Populate some data

For i = 1 to 9
Dr = dt. NewRow ()
Dr (0) = i
DR (1) = "Item" + i.tostring ()
DR (2) = DateTime.Now.ToShortTimeString
If (i Mod 2 <> 0) Then
DR (3) = True
Else
DR (3) = False
End If
' Add data rows to the table
Dt. Rows.Add (DR)
Next

Gridview1.datasource = New DataView (DT)
Gridview1.databind ()
End If
End Sub
The following example shows how to bind to a hashtable.

Sub Page_Load (sender as Object, E as EventArgs)
If not IsPostBack Then
 
Dim h as Hashtable = new Hashtable ()
H.add ("Key1", "value1")
H.add ("Key2", "value2")
H.add ("Key3", "Value3")

Mydatalist.datasource = h
Mydatalist.databind
End If
End Sub
Typically, you might want to process data before you bind to a page or control. The following example shows how to bind to the return value of an expression and a method.

Sub Page_Load (sender as Object, E as EventArgs)
If not IsPostBack Then
Dim values as arraylist= new ArrayList ()

Values. ADD (0)
Values. ADD (1)
Values. ADD (2)
Values. ADD (3)
Values. ADD (4)
Values. ADD (5)
Values. ADD (6)

Datalist1.datasource = values
Datalist1.databind
End If
End Sub

Function evenorodd (number as Integer) as String
If (number Mod 2 <> 0) Then
Return "ODD"
Else
Return "even"
End If
End Function

<asp:datalist id= "DataList1" ... >
<ItemTemplate>
Number Value: <%# container.dataitem%>
Even/odd: <%# evenorodd (Container.DataItem)%>
</ItemTemplate>
</asp:DataList>

Asp. NET page framework component provides a static method that evaluates a deferred binding (late-bound) data-binding expression and optionally formats its result as a string. In this case, DataBinder.Eval is convenient because it eliminates many of the explicit conversions that developers must perform to transfer valuations to the desired data type. It is particularly useful when there are data-bound controls in the templated list, because in that case the data rows and data fields are usually required to be converted.

Take a look at the following example, which needs to display an integer as a currency string. In the standard asp.net data binding syntax, you must first convert the type of the data row to retrieve the data field IntegerValue. It is then passed as a parameter to the String.Format method.

<%# String.Format ("{0:c}", (CType (Container.DataItem, DataRowView) ("IntegerValue"))%>
This grammar is complex and not easy to remember. In contrast, DataBinder.Eval is a simple method with only three parameters: the naming container (naming container) of the data item, the data field name, and the formatted string. In templated controls (such as FormView, GridView, DetailsView, DataList, or Repeater), the naming container is Container.DataItem. A page is a different naming container and can also be used for DataBinder.Eval. As we mentioned earlier, ASP.net 2.0 provides DataBinder.Eval with a new simplified syntax (Eval) that you can use in data-bound control templates to automatically parse Container.DataItem.

<%# DataBinder.Eval (Container.DataItem, "IntegerValue", "{0:c}")%>
<%# Eval ("IntegerValue", "{0:c}")%>
The format string parameter is optional. If this argument is omitted, DataBinder.Eval returns the object type value, as follows:

<%# CType (DataBinder.Eval (Container.DataItem, "Boolvalue"), Boolean)%>
It is important to note that DataBinder.Eval can significantly affect performance compared to the standard data-binding syntax because it uses deferred-bound reflection (reflection). Use DataBinder.Eval wisely, especially if you do not need to format strings.

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.