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.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

asp.net ecommerce said...

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.

Steve Barron said...
This comment has been removed by the author.
Anonymous said...

"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")