Avoid DataBinder.Eval in ASP.NET and improve Performance




I see a lot of developers using DataBinder.Eval, which evaluates data-binding expressions at run time. Although the DataBinder.Eval is quite frequently used in web controls like the GridView, Repeater etc, use it with caution. Here’s what the documentation says

Because this method performs late-bound evaluation, using reflection at run time, it can cause performance to noticeably slow compared to standard ASP.NET data-binding syntax.

Let’s take an example to see how to avoid using DataBinder.Eval. Here’s some code that uses DataBinder.Eval() to display Person details

Although the markup looks tidy, for a large number of rows and columns, you are executing Eval() that many times, which will reduce performance since DataBinder.Eval() uses reflection to evaluate the data-binding expressions.

To avoid using DataBinder.Eval you can use the following alternatives:

For ObjectDataSource

If you are using an ObjectDataSource, refer directly to the Person class as shown below:

<asp:Repeater ID="rptPerson" runat="server">
<
ItemTemplate>
<%# ((Person)Container.DataItem).FirstName %>
<%# ((Person)Container.DataItem).LastName %>
<%# ((Person)Container.DataItem).Age %>
</ItemTemplate>
</
asp:Repeater>

For SqlDataSource

If you are using a SQLDataSource with a DataTable, use the following markup to cast the Container.DataItem as a DataRowView

<asp:Repeater ID="rptPerson" runat="server">
<
ItemTemplate>
<%# ((DataRowView)Container.DataItem)["FirstName"] %>
<%# ((DataRowView)Container.DataItem)["LastName"]%>
<%# ((DataRowView)Container.DataItem)["Age"]%>
</ItemTemplate>
</
asp:Repeater>

Note: If you are using SqlDataSource with the DataReader mode, use DbDataRecord.



Will you give this article a +1 ? Thanks in advance




About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

3 Responses to "Avoid DataBinder.Eval in ASP.NET and improve Performance"
  1. asp.net ecommerce said...
    February 2, 2011 at 4:51 AM

    Thank you very much for this code, I was in search of this info since from long time so glad to have found this post. Really great! Keep posting.

  2. Steve Barron said...
    June 21, 2011 at 10:06 AM
    This comment has been removed by the author.
  3. Anonymous said...
    December 6, 2011 at 5:41 PM

    "Although the markup looks tidy" - well, it code *could* look tidy if it wasn't written .NET 1.1-style with DataBinder.Eval(Container.DataItem, "FirstName") - you only need Eval("FirstName")

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions