Data Binding for ASP. NET 2.0 Advanced Data Processing

Source: Internet
Author: User
In the previous section "data binding in the template", we discussed ASP. net contains a declarative Data Binding syntax used to associate data source fields with control attributes in a data binding template. You can also Code Use the <% #...> syntax to bind any value to the data, such as the page and control attributes, set, expression, and even the return results of method calls. To forcibly calculate the data binding value, you must call the databind method on the page or control that contains the data binding syntax. The following table shows some examples of the Data Binding syntax in ASP. NET.

Single Attribute Customer: <% # custid %>
Set orders <Asp: ListBox id = "list1" datasource = '<% # myarray %> 'runat = "server">
Expression contact <% # (Customer. firstname + "" + customer. lastname) %>
Method Return Value Outstanding balance: <% # getbalance (custid) %>


Although the above syntax looks similar to ASP's response. Write convenient syntax (<% = %>), their behavior is definitely different. The ASP response. Write syntax is used to calculate the value during page processing, while the ASP. NET data binding syntax is used to calculate the value only when the databind method is called.

Databind is a method for page and all server controls. When you call the databind of the parent control, it calls the databind method of all child controls in turn. For example, datalist1.databind () calls the databind method of all controls in the datalist template. Calling the databind method of the page -- page. databind () or simply calling databind () -- triggers calculation of all data binding expressions on the page. Generally, the databind method is called only in the page_load event of the page, as shown in the following example.
In any declarative piece on the. ASPX page, you can use the binding syntax and specify the expected data type for its valuation. The simple attributes, expressions, and methods in the preceding example are displayed to the user when being calculated. In this case, the value of the data binding expression is of the string type. In the preceding collection example, the Value Type of the Data Binding syntax is the datasource attribute of ListBox. You will find that the type of the forced conversion value in the binding expression is necessary to generate the expected result. For example, if count is an integer:

Number of records: <% # Count. tostring () %>

The ASP. NET data binding syntax supports binding public variables, page attributes, and attributes of other controls on the page. The following example demonstrates how to bind a public variable to a simple property of a page. Note that these values have been initialized before databind () is called.

<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 a property to another control:

<Asp: dropdownlist id = "statelist" runat = "server">
<Asp: listitem> Ca </ASP: listitem>
......
</ASP: dropdownlist>

<Asp: button id = "button1" text = "Submit" onclick = "submitbtn_click" runat = "server"/>
Selected State: <asp: Label id = "label1" text = '<% # statelist. selecteditem. Text %> 'runat = "server"/>

List-type server controls (such as dropdownlist, ListBox, and htmlselect) use a set as the data source. The following example shows how to bind a collection type to a universal language runtime. These controls can only be bound to a set 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 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 demonstrates how to bind to dataview. 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

'Create a able
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 )))

'Fill in some data

For I = 1 to 9
Dr = DT. newrow ()
Dr (0) = I
Dr (1) = "item" + I. tostring ()
Dr (2) = datetime. Now. tow.timestring
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 demonstrates how to bind to 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

Generally, you may want to process data before binding to a page or control. The following example shows how to bind the expression to the return value of the 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



number value: <% # container. dataitem %>
even/odd: <% # evenorodd (container. dataitem) %>

The ASP. NET page framework component provides a static method, which estimates the data binding expression of the delayed binding (late-bound) and can choose to format the result as a string. In this case, databinder. Eval is very convenient because it eliminates a lot of Explicit conversions that developers must perform to transfer valuation to the expected data type. It is especially useful when there is a data binding control in the templated list, because in that case, data rows and data fields must be converted.

Let's take a look at the example below. It needs to display the integer as a currency string. In the standard ASP. NET data binding syntax, you must first convert the data row type to retrieve the data field integervalue. Then pass it as a parameter to the string. Format method.


<% # String. Format ("{0: c}", (ctype (container. dataitem, datarowview) ("integervalue") %>

This syntax is complex and hard to remember. In contrast, databinder. Eval is a simple method with only three parameters: naming container, data field name, and formatted string. In templated controls (such as formview, gridview, detailsview, datalist, or repeater), the named containers are all container. dataitem. Page is another named container and can also be used for databinder. eval. As mentioned above, Asp. NET 2.0 is databinder. eval provides a new simplified syntax (eval). You can use it in the data-bound control template to automatically parse the container. dataitem.

<% # Databinder. eval (container. dataitem, "integervalue", "{0: c}") %>
<% # Eval ("integervalue", "{0: c}") %>

The format string parameter is optional. If this parameter is omitted, databinder. Eval returns the object type value, as shown below:

<% # Ctype (databinder. eval (container. dataitem, "boolvalue"), Boolean) %>

We should note that, compared with the standard data binding syntax, databinder. Eval significantly affects performance because it uses reflection ). Use databinder. Eval wisely, especially when strings do not need to be formatted.

This article is reproduced in 'China it Labs'

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.