ASP.net GridView Shortcut

When dealing with Strongly Typed datasets on the ASP.net GridView 2.0, I found myself writing one too many lines of code like this:

<asp:TemplateField HeaderText="Category">
  <ItemTemplate>
  <%# DataBinder.Eval(
    ((System.Data.DataRowView) Container.DataItem).Row,
   "CategoryRow.CategoryName") %>
  </ItemTemplate>
<asp:TemplateField>

Solution?

<asp:TemplateField HeaderText="Category">
  <ItemTemplate>
   <%# EvalEx(Container.DataItem, "CategoryRow.CategoryName") %>
  </ItemTemplate>
<asp:TemplateField>

protected object EvalEx(object DataItem, string Expression)
{
 return DataBinder.Eval(((DataRowView) DataItem).Row, Expression);
}

3 Responses to “ASP.net GridView Shortcut”

  1. Marcie writes:

    Actually there’s a new “Eval” syntax in ASP.NET 2.0 to do this for you:

    Cheers,
    Marcie

  2. Marcie writes:

    Sorry, the code didn’t come through:

    Eval(”CategoryRow.CategoryName”) %>

  3. Chui writes:

    Actual Marcie, the Eval method in 2.0 didn’t quite work

    Eval(”CategoryRow.CategoryName”)

    ASP.net complains that there is no CategoryRow property.

Leave a Reply