Click here to Skip to main content
15,898,035 members
Articles / Web Development / ASP.NET
Tip/Trick

Using Explicit Cast instead of Databinder.Eval to Increase Performance

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
27 Nov 2012CPOL 15.4K   8   2
Increase ASP.NET Application performance with explicit casting

Introduction

The DataBinder.Eval method is used to bind data to a control's template. DataBinder.Eval casts Container.DataItem to its specific type, like this:

ASP.NET
<ItemTemplate>
<div>
<%# DataBinder.Eval(Container.DataItem,"UserName") %>
</div> 
</ItemTemplate>  

DataBinder.Eval uses .NET reflection to cast Container.DataItem to its specific type which results in a performance loss. So it is better to use explicit casting.

Option 1 - Cast the Container.DataItem as a DataRowView if the data source is a DataSet.

ASP.NET
<ItemTemplate> 
<div><%# ((DataRowView)Container.DataItem)["UserName"] %>
</div>
</ItemTemplate>

Option 2 for DataReader

ASP.NET
<ItemTemplate>
<div>
<%# ((DbDataRecord)Container.DataItem)["UserName"] %>
</div>
</ItemTemplate> 

Cast the Container.DataItem as a String if the data source is an Array or an ArrayList.

ASP.NET
<ItemTemplate>
<div>
<%# ((String)Container.DataItem)["UserName"] %>
</div>
</ItemTemplate>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
IT Analyst/ Senior Software Engineer with 4+ years of experience in MS.NET Technologies

Comments and Discussions

 
QuestionMetrics? Pin
fjdiewornncalwe27-Nov-12 4:00
professionalfjdiewornncalwe27-Nov-12 4:00 
AnswerRe: Metrics? Pin
Fenil Desai27-Nov-12 19:35
Fenil Desai27-Nov-12 19:35 
@Marcus, since it was just a tip so didn't added any metrics..
will try to add if possible..

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.