What's the deal with Databinder.Eval and Container.DataItem? - Raj Kaimal

What's the deal with Databinder.Eval and Container.DataItem?

Reposting here for the benefit of asp.net developers and Google

The databinding expression <%# some expression %> is evaluated in the language of the page (VB, C#, etc.)  This can have a big impact on the current syntax, so be very careful when you are looking at docs for the language you are using.

 

Container.DataItem is a runtime alias for the DataItem for this specific item in the bound list.  For a grid which displays 10 rows of data, this is one row from the datasource.  The actual type of DataItem is determined by the type of the datasource.  For example, if the datasource is a Dataview, the type of DataItem is DataRowView.  If the type of the datasource is an array of strings, the type of DataItem is String.  If the datasource is a collection of strongly-typed objects (for example "Employees" objects), the type of DataItem is Employees.

 

Each of these cases requires a slightly different databinding expression, with further differences between VB and C#.  In every case, you want the databinding expression to produce a string that can be displayed in the page.

 

Here are some examples:

 

Array of Strings:

VB/C# <%# Container.DataItem %>

 

Field from DataView:

VB      <%# Container.DataItem("EmployeeName") %>

C#      <%# ((DataRowView)Container.DataItem)["EmployeeName"] %>

 

Property from a collection of objects:

VB      <%# Container.DataItem.CustomerName %>

C#      <%# ((Customer)Container.DataItem).CustomerName %>

 

Non-String property from a collection of objects:

VB      <%# CStr(Container.DataItem.CustomerID) %>

C#      <%# ((Customer)Container.DataItem).CustomerID.ToString() %>

 

 

As you can see the syntax is tricky, especially for C#, which requires explicit casting. So we've provided a DataBinder.Eval() helper method that figures out the syntax for you and formats the result as a string. It's really convenient, with a couple of caveats: it's late bound (uses reflection at runtime to figure out the data types), and it only supports basic data types in the fields: string, int, datetime, etc.

You can use Eval instead of DataBinder.Eval in ASP.net 2.0

  

DataBinder.Eval takes 2 or 3 arguments.  The first arg is the data object to bind to.  In the case of DataGrid, DataList and Repeater, Container.DataItem is the single row.  The second arg the string name of the field from the data object you which to display.  DataBinder.Eval uses these two pieces of information to work out the rest of the expression syntax.

 

An optional third argument is a .NET formatting string.  DataBinder.Eval will handle a single replacement for {0} only.  So the example below:

 

<a href='<%# "default.aspx?CategoryId=" + Cstr(Databinder.Eval(Container.DataItem, "ID"))%>'>


could be simplified to:


<a href='<%#  Databinder.Eval(Container.DataItem,"ID","default.aspx?CategoryId={0}" ) %>'>

 

Wrapping DataBinder.Eval in CStr() is unnecessary as the compiler will wrap the statement with a Convert.ToString like this:

control1.SetDataBoundString(0, Convert.ToString(DataBinder.Eval(item1.DataItem, "ID")));

 

Best of all, the Databinder.Eval syntax is the same for VB and C#.
 

Susan Warren
11/30/2000 1:48:00 PM

Comments:
Scott Galloway
Worth mentioning the performance cost of this, in my own tests I've found around 20% performance loss in using DataBinder.Eval versus explicit casting. This can make a difference when binding large sets. My original post on this is here: http://www.mostlylucid.co.uk/archive/2003/12/09/664.aspx


References:

DataBinder.Eval Method


Google Google

Published Tuesday, July 20, 2004 12:32 PM by rajbk
Filed under:

Comments

# re: What's the deal with Databinder.Eval and Container.DataItem?

The problem with explicit casting is that if you change your data layer you have to go in every single page that uses it and change it. Using reflection doesn't have this problem.

Tuesday, July 20, 2004 7:12 PM by Jerry Pisk

# re: What's the deal with Databinder.Eval and Container.DataItem?

Jerry, the same could be said about any strongly typed language - VBScript had variants only, made things really easy to change but you could get in a muddle really easily and end up with all sorts or runtime errors. I prefer the strongly typed approach and I have to say I don't find any increased maintainance costs associated with this.

Wednesday, July 21, 2004 8:18 AM by Scott Galloway

# DataBinder and DataItem

Tuesday, July 27, 2004 11:45 PM by TrackBack

# re: What's the deal with Databinder.Eval and Container.DataItem?

how colud i do this

<%if(DataBinder.Eval(Container.DataItem,"WPID")>0){%>

Requested Before.

<%}else{%>

<INPUT id=chkImage type=checkbox value='<%# DataBinder.Eval(Container.DataItem,"WPID") %>' name=chkImage>&nbsp;Request Image

<%}%>

Monday, September 11, 2006 4:20 AM by Mohamed Magdy

# re: What's the deal with Databinder.Eval and Container.DataItem?

Thanks... very helpful.

Wednesday, September 27, 2006 2:08 AM by Kevin

# re: What's the deal with Databinder.Eval and Container.DataItem?

Thanks !!

I learnt valuable information from ur article.Keep doing Such activities.

                                     Regards

Tuesday, December 19, 2006 5:27 AM by Girish

# re: What's the deal with Databinder.Eval and Container.DataItem?

Thanks... very useful article.

Tuesday, December 19, 2006 10:02 PM by Arun Rajan

# re: What's the deal with Databinder.Eval and Container.DataItem?

You just saved me with this one. Thanks!!

Wednesday, December 27, 2006 3:02 AM by Bret

# re: What's the deal with Databinder.Eval and Container.DataItem?

Is there any way I can evaluate one of those expressions? This is what I'd like to do:

<%# If DataBinder.Eval(Container.DataItem, "DATAFIELD") <> "" Then

    Response.Write("something")

End If %>

Wednesday, January 31, 2007 8:31 AM by Sergio

# re: What's the deal with Databinder.Eval and Container.DataItem?

Description about this topic is easy understable and meaning full Thanks

Friday, February 23, 2007 6:42 AM by Rajesh Domadia

# re: What's the deal with Databinder.Eval and Container.DataItem?

Nice concise and good description. One thing was puzzling me though, how come theres no overloaded method that just takes a single parameter ie the Datafield string, and internally generates a reference to the Container.DataItem.

Friday, March 30, 2007 8:30 AM by Mickey Puri

# re: What's the deal with Databinder.Eval and Container.DataItem?

Very helpful solved my problem. Thanks

Wednesday, April 11, 2007 11:46 AM by Paresh Dehadray

# re: What's the deal with Databinder.Eval and Container.DataItem?

Thanks, good article

Thursday, April 26, 2007 8:43 PM by Alejandro Fern&#225;ndez A.

# re: What's the deal with Databinder.Eval and Container.DataItem?

Thanks, that's a very easy to read and understand article and it helped fill in the gaps of my knowledge. i've been typing all this stuff out for years but have never both to find out what the code is actually doing. cheers for making it clearer.

Tuesday, May 22, 2007 9:13 AM by Pete

# re: What's the deal with Databinder.Eval and Container.DataItem?

Answering the question....

<%# If DataBinder.Eval(Container.DataItem, "DATAFIELD") <> "" Then

   Response.Write("something")

End If %>

Try this....

<%# DataBinder.Eval(Container.DataItem, "DataField").Equals("")?"":"Something"%>

Thursday, August 02, 2007 11:23 PM by someone

# re: What's the deal with Databinder.Eval and Container.DataItem?

Hi, when I put this code get the error message writen in title: dataitem is not a member of System.Web.UI.PageataItem.

<asp:DataGrid ID=dgDuznici runat=server HeaderStyle-BackColor=#dddde7 ItemStyle-BackColor=#ebeaef AutoGenerateColumns=false BorderColor=black>

    <Columns>

     <asp:TemplateColumn HeaderText="Za brisanje">

      <ItemTemplate>

       <asp:CheckBox ID=chkSelection runat=server Checked=false />

      </ItemTemplate>

     </asp:TemplateColumn>

     <asp:TemplateColumn HeaderText="Li&#269;ni ra&#269;un">

      <ItemTemplate>

       <asp:Label ID=lblLicniRacun runat=server Text='<%# DataBinder.Eval(Container.DataItem, "licni_racun")%>' />

      </ItemTemplate>

     </asp:TemplateColumn>

    </Columns>

   </asp:DataGrid>

What is the problem?

Wednesday, September 05, 2007 3:15 PM by dragy

# re: What's the deal with Databinder.Eval and Container.DataItem?

Very nice article. Thanks

Tuesday, September 18, 2007 4:50 AM by sumanth

# re: What's the deal with Databinder.Eval and Container.DataItem?

I tried this

Text='<%# If DataBinder.Eval(Container.DataItem, "CARRIER_NAME").Equals("") Then Response.Write("Some") End If %>

But found this Error:

BC30201: Expression expected

Thursday, September 20, 2007 7:24 AM by Omprakash Pal.

# re: What's the deal with Databinder.Eval and Container.DataItem?

I tried this

<%# DataBinder.Eval(Container.DataItem, "DataField").Equals("")?"":"Something"%>

But found the Error:

BC30037: Character is not valid.

Plz suggest me the solution.

Thanx in advance.

Thursday, September 20, 2007 7:41 AM by Omprakash Pal.

# re: What's the deal with Databinder.Eval and Container.DataItem?

Does Anyone know how to pass a whole Row into a Function? Something like this

Function ParseData(ByVal oRow As RepeaterItem)

Return oRow.Item("FieldName")

End Function

<asp:repeater....

<ItemTemplate>

<#ParseData(Container.DataRow)%>

</ItemTemplate>

</asp:repeater>

Friday, September 28, 2007 5:10 AM by Mr Maccoy

# re: What's the deal with Databinder.Eval and Container.DataItem?

Omprakash Pal:

I usually put something like

<%# comparisonFunction(DataBinder.Eval(Container.DataItem, "DataField")%>

and then make a function:

private string comparisonFunction(string criteria)

{

if (criteria<0)

{

return "this is less than 0";

}

else

{

return "this is greater than or equal to 0";

}

}

or whatever.  If you are thinking of adding controls to the page it would based on criteria like Mohamed Magdy was trying to do, I'd put that code in the event handler that would be the trigger for that control to appear.  Put a place holder on the page (if there isn't a control you're adding it to) and use the placeholder.Controls.Add method.

in the case that he mentioned above:  you could add a label with the text that your want if one thing happened, otherwise you could add the checkbox.  

Friday, November 09, 2007 8:27 AM by Big Bad Bart

# re: What's the deal with Databinder.Eval and Container.DataItem?

Thanks for the clarification.  This saved me some headaches.  I was actually Googled for info on creating custom DataItem controls and found this article instead.  After I finally created my custom object, I got a databinding error but was able to quickly fix it since I "accidentally" found this article previously.

Thanks again.

Friday, November 09, 2007 11:41 AM by FelixPerro

# re: What's the deal with Databinder.Eval and Container.DataItem?

Cheers, very helpful

Friday, November 30, 2007 10:53 AM by dbones

# re: What's the deal with Databinder.Eval and Container.DataItem?

Is it possible to bind 2 or 3 dimensional arrays to data controls If so, can u help me out with the syntax??

Thursday, December 13, 2007 12:53 AM by Kisna

# re: What's the deal with Databinder.Eval and Container.DataItem?

Does anyone know why

<%#DataBinder.Eval(Container, "ItemIndex").ToString%>

works from within a Datalist (Datalist1) item to give me the ItemIndex in the aspx during binding, but the same code does not work in a child nested Datalist (Datalist2)? When used in a nested Datalist (Datalist2), <%#DataBinder.Eval(Container, "ItemIndex").ToString%> gives me the ItemIndex of Datalist1.

Cheers for any help.

Wednesday, January 09, 2008 10:39 PM by Barnarse

# re: What's the deal with Databinder.Eval and Container.DataItem?

Cheers, very helpful

Ray Akkanson

Thursday, January 10, 2008 12:39 PM by Ray Akkanson

# re: What's the deal with Databinder.Eval and Container.DataItem?

very good article...keep it up

Friday, January 11, 2008 6:41 AM by deepak

# re: What's the deal with Databinder.Eval and Container.DataItem?

Just wanted to add my thanks.

Sunday, February 03, 2008 3:47 PM by VJ

# re: What's the deal with Databinder.Eval and Container.DataItem?

Thanx it's very helpful

Tuesday, February 19, 2008 5:41 AM by Shivendra

# re: What's the deal with Databinder.Eval and Container.DataItem?

Nice article.

To avoid databinder.eval which has the Reflection overhead to type the data, we could strongly type the Container.DataItem in VB.NET as follows

<%# (CType(Container.DataItem, System.Data.DataRowView)("fieldname")) %>

In case of date formats,

<%# (CType(Container.DataItem, System.Data.DataRowView)("datecolumn")).ToShortDateString() %>

Wednesday, February 20, 2008 1:43 PM by Srikanth

# re: What's the deal with Databinder.Eval and Container.DataItem?

This is what i have been wanting for months. Thx a lot !

Monday, February 25, 2008 8:53 AM by Karthik ananth

# re: What's the deal with Databinder.Eval and Container.DataItem?

Hello thanks for this article!

One Question:

Is it possible to give him informations through the eval?

This works:

Property from a collection of objects:

VB      <%# Container.DataItem.CustomerName %>

But i need something like this:

Container.DataItem.CustomerName("Information")

I need a way to pass a string too! For example get the customer depending on the ID or something.

E.G.: Container.DataItem.CustomerName("ID")

Is that possible?

Greetings!

Monday, March 17, 2008 5:20 AM by Matthias

# re: What's the deal with Databinder.Eval and Container.DataItem?

Thank you this was very helpful!

Tuesday, March 25, 2008 2:37 PM by Aaron

# re: What's the deal with Databinder.Eval and Container.DataItem?

helped me a lot..thanks

Wednesday, March 26, 2008 12:29 AM by srivastav

# re: What's the deal with Databinder.Eval and Container.DataItem?

Hi,

In DataBinder.Eval method, I have to pick up the column name which is created dynamically...How can I do this?

e.g.

1) When I am sure that my column name is Product_No, then I can use

'<%#DataBinder.Eval(Container, "DataItem.Product_No")%>'

2) What if my column name is generated dynamically in the table, and I need to pick up that COLUMN NAME in this method???

Please help

Wednesday, May 07, 2008 9:56 AM by Tushar

# re: What's the deal with Databinder.Eval and Container.DataItem?

<a href='<%#  Databinder.Eval(Container.DataItem,"ID","default.aspx?CategoryId={0}" ) %>'>

How to pass one more query string?

Wednesday, May 28, 2008 8:20 AM by Jiju Alex

# re: What's the deal with Databinder.Eval and Container.DataItem?

Jiju this is for you

<a href='<%#

String.Format("default.aspx?CategoryId={1}&ProductId={0}",Eval("catid"),Eval("proid"))

%>'

Friday, June 06, 2008 8:25 PM by usama

# re: What's the deal with Databinder.Eval and Container.DataItem?

Thank you!  This is working for me:

<ItemTemplate>

<a href='<%#String.Format("invdetail.aspx?lot={0}&siteid={1}",DataBinder.Eval(Container,"DataItem.lotno"),DataBinder.Eval(Container,"DataItem.siteid"))%>'>

<%#DataBinder.Eval(Container,"DataItem.lotno")%></a>

</asp:Literal>

</ItemTemplate>

Monday, June 16, 2008 11:21 AM by Suzy

# re: What's the deal with Databinder.Eval and Container.DataItem?

For people who want to use if, else if else inside a <% using the Container.DataItem

it won't work

a workaround I created is this

in your .cs file

public static string PrintStuff(object obj){

 // if its a class

 YourClass x = (YourClass)obj;

 return YourClass.YourProperty;

}

my .aspx files only uses classes, all my DB stuff is behind the classes, so this worked ok for me

maybe someone can put other alternative or using DataBase stuff

hope this helps,

Joe

Tuesday, June 24, 2008 5:40 PM by Jonathan

# re: What's the deal with Databinder.Eval and Container.DataItem?

I am developing a custom control, where I add Columns dynamically to an encapsulated DataGrid. I use following code to add a Template Column:

           Dim email As New TemplateColumn

           email.HeaderText = "Email"

           email.ItemTemplate = New UI.CompiledTemplateBuilder(New UI.BuildTemplateMethod(AddressOf Me.buildEmailTemplate))

           Me.grid.Columns.Add(email)

       Private Sub buildEmailTemplate(ByVal container As Control)

           Dim label As New Label

           container.Controls.Add(label)

           AddHandler label.DataBinding, New EventHandler(AddressOf Me.emailDataBinding)

       End Sub

       Private Sub emailDataBinding(ByVal sender As Object, ByVal e As EventArgs)

           Dim label As Label = CType(sender, Label)

           'label.Text = Common.Formatter.formatEmail(label.Parent.dataitem)

       End Sub

Both buildEmailTemplate & emailDataBinding methods are invoked for each row, when the Grid is DataBound. However, I could not get to the DataItem property in any way, so that I can suitably format & display the email.

So, how & where should I evaluate Container.DataItem for a dynamically added template column???

Thursday, June 26, 2008 10:41 PM by r_honey

# re: What's the deal with Databinder.Eval and Container.DataItem?

Why i cannot simply say <%# Eval("DB_Field") %>

I mean this works for me but does it mean that i should avoid it and use Container.DataItem ??

Thanks

Sunday, June 29, 2008 9:34 AM by yugolancer

# re: What's the deal with Databinder.Eval and Container.DataItem?

Good stuff!

Tuesday, July 01, 2008 6:53 PM by Joe Schlubb

# Ultracet.

Is ultracet addictive. Ultracet. Is ultracet a narcotic. Ultracet buzz.

Sunday, July 27, 2008 10:53 AM by Ultracet.

# re: What's the deal with Databinder.Eval and Container.DataItem?

Hats of to you,Really Nice article which gives lot of information in a simple language.

Keep doing this work...

Saturday, August 16, 2008 8:47 AM by arun

# re: What's the deal with Databinder.Eval and Container.DataItem?

<div class="divCell ObsArabil">

<asp:Label runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Comments")%>' ID="lbleArabilComments" CssClass="Label SmallSize">

</asp:Label>

&nbsp;

</div>

AND THE RESULT IS SOMETHING LIKE THIS

28.08.2008:TEST

HOW I MAKE TO WRITE JUST TEST?

Tuesday, August 26, 2008 8:49 AM by DAN

# re: What's the deal with Databinder.Eval and Container.DataItem?

Its a useful article..thanks

Friday, September 19, 2008 4:16 AM by Ramakrishna.B.V

# re: What's the deal with Databinder.Eval and Container.DataItem?

The article is a useful and easy to understand,it helped me a lot,i appreciate you to contiune and thank you.

Wednesday, October 22, 2008 11:13 AM by baski

# re: What's the deal with Databinder.Eval and Container.DataItem?

Thank you very much,

I understand how to use the function in databinder with container.DataItem

Friday, October 24, 2008 3:39 PM by baski

# re: What's the deal with Databinder.Eval and Container.DataItem?

It is the simple concepts like this that are skipped by a lot of books and tutorials leading to misunderstanding when learning ASP.NET. Thanks.

Wednesday, December 03, 2008 4:36 AM by Tristan Margot

# re: What's the deal with Databinder.Eval and Container.DataItem?

I found out about this entry about 2 years ago (and saved my life back then), and I still come back to remember how to use it from time to time. Thanks!

Thursday, January 08, 2009 1:22 AM by Kaz

# re: What's the deal with Databinder.Eval and Container.DataItem?

I want to keep a if and else condition in the code below

<td align="left" style="width:80%">

                         <%# ((System.Data.DataRowView)Container.DataItem)["company"]%>

                         <%# ((System.Data.DataRowView)Container.DataItem)["keywords"]%>

                       </td>

i have two radio button and on 1st radiobutton check i want to show only 1st coloumn data

and on check of 2nd i want to show only 2nd column of data

can anybody help me how to do it.

please its urgent..

Saturday, January 17, 2009 5:06 AM by jitendra

# re: What's the deal with Databinder.Eval and Container.DataItem?

Best for me is:

NavigateUrl='<%# "?projectdid=" + Container.DataItem("SITE_ID").toString() %>'

Saturday, January 17, 2009 7:03 AM by Esref Atak (Vukuf)

# what really is &lt;%# %&gt;, does Eval, Bind needed? | keyongtech

Pingback from  what really is &lt;%# %&gt;, does Eval, Bind needed? | keyongtech

# re: What's the deal with Databinder.Eval and Container.DataItem?

As a newbie to .NET coming from ASP Classic, I'm trying to use cimilar syntax to refer to columns in my data source but I am accustomed to using ordinal references, instead of column aliases.  How can this be achieved in .NET using a data display control?  I haven't found anything on it and I hope it didn't get axed since it's an overhead issue in so many ways.

Monday, February 09, 2009 3:04 PM by Nick Owens

# re: What's the deal with Databinder.Eval and Container.DataItem?

what if I am binding it to an array, multidimensional or jugged arrays, any idea about how to do that?

Thanks

Wednesday, February 11, 2009 2:32 PM by Hazım

# re: What's the deal with Databinder.Eval and Container.DataItem?

nice, really nice!

Thursday, April 16, 2009 7:27 PM by DevareattyVaH

# re: What's the deal with Databinder.Eval and Container.DataItem?

Great post!! Finally found what I was looking for!

Wednesday, April 22, 2009 3:06 AM by Randy

# re: What's the deal with Databinder.Eval and Container.DataItem?

For those who asked the questions about dynamically added columns, did you find an answer?

Specifically r_honey, my code's doing the same as yours and I can't find anywhere to access dataitem from any of my containing controls.

Saturday, May 23, 2009 8:25 AM by Kurt Farrar

# re: What's the deal with Databinder.Eval and Container.DataItem?

this is a very good article which is simply saying the conceptual things...it really helps...keep doing..all the best...

Sunday, May 31, 2009 2:17 AM by udeep

Leave a Comment

(required) 
(required) 
(optional)
(required)