Single attribute | Customer: <%# custID %> |
Collection Orders | <asp:ListBox id="List1" datasource='<%# myArray %>' runat="server"> |
Expression Contact | <%# ( customer.FirstName + " " + customer.LastName ) %> |
The return value of the method | Outstanding Balance: <%# GetBalance(custID) %> |
Although the above syntax looks similar to ASP's Response.Write convenience syntax (<%= %>), their behavior is But it's definitely different. The ASP Response.Write convenience syntax calculates the value while the page is processing, while the ASP.NET data binding syntax only calculates the value when the DataBind method is called.
DataBind is a method of the page and all server controls. When you call the DataBind of the parent control, it will call the DataBind method of all child controls in turn. For example, DataList1.DataBind() will call the DataBind method of all controls in the DataList template. Calling the page's DataBind method -- Page.DataBind() or simply calling DataBind() -- causes the evaluation of all data binding expressions on the page. The DataBind method is usually only called in the Page_Load event of the page, as shown in the following example.
In any declarative section of an .aspx page, you can use binding syntax and specify the data type expected by the runtime for its evaluation. The simple properties, expressions, and methods in the examples above display text content to the user when evaluated. In this case, the value of the data binding expression is of type String. In the collection example above, the value type of the data binding syntax is the DataSource property of the ListBox. You will find that casting the type of the value in the binding expression is necessary to produce the desired results. For example, if count is an integer:
Number of Records: <%# count.ToString() %>
ASP.NET data binding syntax supports binding of public variables, page properties, and properties of other controls in the page. The following example demonstrates how to bind to public variables and simple properties of the page. Please 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 demonstrates 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" 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 collections as data sources. The following example demonstrates how to bind to a common language runtime collection type. These controls can only be bound to collections that support the Ienumerable, Icollection, or IlistSource interfaces. More commonly, it can be bound to ArrayList, Hashtable, DataView and DataReader. The following example demonstrates how to bind to an 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 SubThe
following example demonstrates 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
'Create 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)))
'Fill in 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 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 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
Often, you may want to process data before binding to the page or control. The following example demonstrates how to bind to expressions and method return values.
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>
The ASP.NET Page Framework component provides a static method that evaluates a late-bound data binding expression and optionally formats the result as a string. In this case, DataBinder.Eval is convenient because it eliminates much of the explicit conversion work that the developer must perform to convert the estimate to the desired data type. It is particularly useful when there are data-bound controls in a templated list, because in that case usually both the data rows and the data fields must be converted.
Take a look at the following example, which needs to display an integer as a currency string. In standard ASP.NET data binding syntax, you must first convert the type of the data row 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 very complicated and not easy to remember. In contrast, DataBinder.Eval is a simple method with only three parameters: the data item's naming container, the data field name, and the format string. In templated controls (such as FormView, GridView, DetailsView, DataList, or Repeater), the named container is Container.DataItem. Page is another named container that can also be used for DataBinder.Eval. As we mentioned earlier, ASP.NET 2.0 provides a new simplified syntax (Eval) for DataBinder.Eval, which 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 parameter is omitted, DataBinder.Eval will return an Object type value, as shown below:
<%# CType(DataBinder.Eval(Container.DataItem, "BoolValue"), Boolean) %> What
we should pay attention to is that, with the standard Compared with the data binding syntax, DataBinder.Eval will significantly affect performance because it uses lazy binding reflection. Please use DataBinder.Eval wisely, especially if you don't need to format the string.