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

Databinder.Eval using Lamda Expressions

0.00/5 (No votes)
7 Apr 2010 1  
Using lambda expression to help with compile time checking of Eval statements

Introduction

We all have done it, and we all know how it can be frustrating when dealing with magic strings. While not terribly hard to fix or work around, the Databinder.Eval("") method needs to use strings in order to work. However, using some extension methods (or a helper class) can remove the dependency on these magic strings and allow your code to use lambda expressions instead.

Using the Code

public static class ExtensionMethods
{
    public static string Evaluate<T>(this ListViewItem item, 
	Func<T, object> expression)
    {
        var result = expression((T)item.DataItem);
        if (result != null)
            return result.ToString();
        return null;
    }

    public static TOutput Evaluate<T, TOutput>
	(this ListViewItem item, Func<T, TOutput> expression)
    {
        return (TOutput)expression((T)item.DataItem);
    }
}		 

So, with these, instead of using code that looks like this:

 <asp:GridView ID="gvName" runat="server" AutoGenerateColumns="False" 
        HorizontalAlign="Center">
      <Columns> 
          <asp:TemplateField HeaderText="County Name">               
              <ItemTemplate>
                  <%# Eval("County.Name") %>
              </ItemTemplate>
          </asp:TemplateField>            
      </Columns>
 </asp:GridView> 

You can use the slightly more verbose, but more stable lambda version:

 <asp:GridView ID="gvName" runat="server" AutoGenerateColumns="False" 
	HorizontalAlign="Center">
   <Columns> 
     <asp:TemplateField HeaderText="County Name">               
       <ItemTemplate>
         <%# Container.Evaluate<AddressEntity>(c=>c.County.Name) %> 
       </ItemTemplate>
     </asp:TemplateField>            
   </Columns>
</asp:GridView>  

Points of Interest

Just remember to include the namespace of wherever you placed your code either at the top of the page or in the web.config.

The second version of the Evaluate method allows you to return the data typed as it actually is instead of returning it as the string. This is useful if you need to call page methods and don't want to cast it once to a string with Eval(), then recast it back.

<%# DoSomething(Container.Evaluate<AddressEntity, int?>(c=>c.County.CountyID)) %>   

History

  • 04/07/2010 - Original draft

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