DataBinder.Eval
The ASP.NET framework 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, because often 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.NET 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}", (CType(Container.DataItem, DataRowView)("IntegerValue"))) %>
VB
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}") %>
VB
The format string argument is optional. If it is omitted, DataBinder.Eval returns a value of type object, as shown in the following example.
<%# CType(DataBinder.Eval(Container.DataItem, "BoolValue"), Boolean) %>
VB
It is important to note that DataBinder.Eval can carry a noticeable performance penalty over the
standard data binding syntax because it uses late-bound reflection. Use DataBinder.Eval judiciously, especially when string
formatting is not required.
Section Summary
- The ASP.NET declarative data binding syntax uses the <%# %> notation.
- You can bind to data sources, properties of the page or another control, collections, expressions, and results
returned from method calls.
- List controls can bind to collections that support the ICollection, IEnumerable, or IListSource interface, such as ArrayList, Hashtable,
DataView, and DataReader.
- DataBinder.Eval is a static method for late binding. Its syntax can be simpler than the standard data
binding syntax, but performance is slower.
Copyright 2001-2002 Microsoft Corporation. All rights reserved.