Container.DataItem or DataBinder.Eval

J

JohnZing

Hi,
Should I use
<%# Container.DataItem("Author")%>
or
<%# DataBinder.Eval(Container.DataItem,"Author") %>

What's the difference between both?
Thank You
 
W

Wilco Bauwer

DataBinder.Eval uses reflection to get a value of a property of the
dataitem object. This is less performant than casting the dataitem
object to its actual type, and then access its property. The only
reason to use DataBinder.Eval is that the syntax may be/look simpler.

I always cast it to its actual type, which means it looks like this:
<%# ((MyObject)Container.DataItem).MyProperty %>
Or in case you are binding against a datatable, the dataitem is of the
the type datarowview:
<%# ((DataRowView)Container.DataItem)["MyField"] %>
 
S

Scott Allen

Hi John:

The DataItem property returns a reference to an object, and
System.Object doesn't have an indexer defined. You'd have to cast the
DataItem return value to the proper type before the first expression
would compile.

DataBinder.Eval works because it will use reflection to dig out the
property with the name of "Author" dynamically. The second expression
would be the one to use in this case because it is the only one to
work.

There are some more details and alternatives here:
http://odetocode.com/Articles/278.aspx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top