Databinding expressions declaratively create bindings between server control properties and data sources. Databinding expressions can be written either on the value side of a name/value pair:
<tagprefix:tagname property="<%# databinding expression %> runat="server" />
or inline within literal text:
literal text <%# databinding expression %>
ASP+ supports a hierarchical databinding model that supports associative bindings between server control properties and parent data sources. Any server control property can be databound. Control properties can databind against any public field or property on either the containing page or their immediate naming container.
The Web Forms framework also supplies a static method that evaluates late-bound data binding expressions and optionally formats the result as a string. DataBinder.Eval
is convenient in that it eliminates much of the explicit casting the developer must do to coerce values to the desired data type. It is particularly useful when data binding controls within a templated list, since often the both the data row and the data field must be cast.
Consider the following example, where an integer will be displayed as a currency string. With the standard ASP+ data binding syntax, you must first cast the type of the data row in order to retrieve the data field, IntegerValue. Next, this is passed as an argument to the String.Format
method:
<%# String.Format("{0:c}", ((DataRowView)Container.DataItem)["IntegerValue"]) %>
This syntax can be complex and difficult to remember. In contrast, DataBinder.Eval
is simply a method with three arguments: the naming container for the data item, the data field name, and a format string. In a templated list like DataList, DataGrid or Repeater the naming container is always Container.DataItem. Page is another naming container that can be used with DataBinder.Eval
.
<%# DataBinder.Eval(Container.DataItem, "IntegerValue", "{0:c}") %>
The format string argument is optional. If it is omitted, DataBinder.Eval
returns a value of type object. For example:
<%# (bool)DataBinder.Eval(Container.DataItem, "BoolValue") %>
<html> <script language=”VB” runat=server> Sub Page_Load(Sender as Object, E as EventArgs) MyOrderSystem as New OrderSystem MyRepeater.DataSource = MyOrderSystem.GetOrdersFromDay(Now) MyRepeater.DataBind() End Sub </script> <body> <form action=”DatabondPage.aspx” method=”post” runat=server> <asp:repeater id=”MyRepeater” runat=server> <template name=”itemtemplate”> <img src=”<%# Container.DataItem.ImageUrl %>” runat=server> <b> Description: </b> <%# Container.DataItem.Description %> </template> </asp:repeater> </form> </body> </html>
ASP+ Page Syntax