I'm trying to understand how Eval() works for a specific purpose. I'm working on a project I don't really know and I need to read some data and put them in drop down list. These data are already read and are displayed inside an ItemTemplate. I noticed there are read using the Eval() method. Something like:
<ItemTemplate>
<a href="...=<%# Eval("foo") %>></a>
</ItemTemplate>
I need to know where Eval is getting these data from in order to discover where I should read them for my drop down list! But I didn't really understand how it works! I know that Eval() evaluates data binding expressions at runtime but where do you think I should take a look at?
Thank you
The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string.
Difference between Eval and Bind function in ASP.Net 2. Eval function is used to bind data to control inside a DataBound control, but it cannot update the values back to the database. Bind function can be used to bind data to control inside a DataBound control and also it can update the values back to the database.
Evaluates data-binding expressions at run time and formats the result as a string.
Eval) function is used to bind data in controls inside GridView, DataList, Repeater, DetailsView, etc. and using string. Format multiple values can be set to a single control. HTML Markup. The below HTML Markup consists of an ASP.Net GridView with 4 columns.
This is a good resource: http://bytes.com/topic/asp-net/answers/447041-databinder-eval-mystification
Some reasons why to avoid it: http://weblogs.asp.net/jgalloway/archive/2005/09/20/425687.aspx
One way to improve by explicit cast: http://dotnettipoftheday.org/tips/use-explicit-casting-instead-of-databinder.eval.aspx
HTH.
Eval
is a shortcut, sort of. It is an actual method call, though, unlike Bind
, which is more like a code snippet.
The MSDN article on Data-Binding Expressions should give you a really good overview.
Put simply, the parser, when it reads the page, calls DataBinder.Eval and passes in the current DataItem in context along with the string you're specifying. It's a lot like reading columns from a DataReader.
The DataItem in context depends on where this is happening. In, say, a GridView, this will probably be like a DataRow object in a DataTable that the GridView was bound to, but it can be any object really since it works via reflection. In the case of a DataRow, Eval("Foo") would try to extract data from the Foo column of the DataRow.
You can see now where this could go bad. If the DataRow stops including a Foo column, then the Eval call will fail miserably but not until runtime since there is no strong type/name checking involved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With