Avoiding DataBinder.Eval in ASP.NET
I've used this tip at least thrice, so following Phil's "Rule of Three" it's time to do something with it. Link to it now, I shall.
It would be easy to pass this one up if you're not using ASP.NET 2.0, but this is applicable for ASP.NET 1.x, too. Key points:
- The DataBinder.Eval syntax uses reflection and should be avoided if you can determine the object type at design time (see Scott Galloway's writeup on this here and here).
- A quick way to see what the Container object holds is to bind directly to it: <asp:Label ID="Label2" runat="server" Text='<%# Container.DataItem%>'></asp:Label>
Sure, the syntax got easier. Instead of the cumbersome:
<%# DataBinder.Eval(Container.DataItem, "url") %>
We get to save some strokes and remove the entire confusion around “what the heck is Container.DataItem?“:
<%# Eval("url") %>
But, this isn't all its cracked up to be. Eval() STILL uses reflection to evaluate expressions, therefore for every bound column/row displayed in your ASP.NET pages, you are adding overhead, unnecessarily. Of course, what this really means is, just like with 1.1, you should be using explicit casts to cast Container.DataItem to its actual type:
<%# ((System.Data.DataRowView)Container.DataItem)["url"]) %>
Of course the trick is to know...you guessed it...what the heck is Container.DataItem??? A quick way to find this out for various objects you may choose to employ in binding, is to bind just to Container.DataItem as a test. In the attached example I bound the GridView control to the Web configuration sections:
Configuration webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSectionCollection webConfigSections = webConfig.Sections;
GridView1.DataSource = webConfigSections;
In the GridView declaration I included these labels in a template column:
<asp:Label ID="Label2" runat="server" Text='<%# Container.DataItem%>'></asp:Label>:
<asp:Label ID="Label3" runat="server" Text='<%# ((ConfigurationSection)Container.DataItem).SectionInformation.SectionName %>'></asp:Label>
Now you can consider yourself early bound.
ConfigurationUtility.zip (60.58 KB)