Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Using Explicit Cast instead of Databinder.Eval to Increase Performance

0.00/5 (No votes)
27 Nov 2012 1  
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:

<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.

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

Option 2 for DataReader

<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.

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here