Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net Databinding - Referencing Anonymous Type Properties

I have bound an ASP.net GridView to a collection of anonymous types.

How can I reference one of the properties of the anonymous types in the RowDataBound event handler?

I am already aware of the way to cast the anonymous type like this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var AnonObj = Cast(e.Row.DataItem, 
          new { StringProperty = "", BoolProperty = false, IntProperty = 0 });

        if (AnonObj.BoolProperty)
        {
            e.Row.Style.Add(HtmlTextWriterStyle.Color, "Red");
        }
    }
}


T Cast<T>(object obj, T type)
{
    return (T)obj;
}

I think most would say this is messy, even though it does work. In my real code, I have more than 3 properties and I would have to update code in two places anytime I added or reordered the properties of my anonymous type.

Is there a better way to tell e.Row.DataItem that it has a specific property of a specific type and force the object to give me that value (besides creating a class)?

like image 511
Ronnie Overby Avatar asked Nov 30 '22 12:11

Ronnie Overby


2 Answers

Look into using reflection.

Example:

object o = e.Row.DataItem;
Type t = o.GetType();
PropertyInfo pi = t.GetProperty("StringProperty");
if (pi != null && pi.PropertyType == typeof(string))
{
  // the property exists!
  string s = pi.GetValue(o, null) as string;
  // we have the value
  // insert your code here
  // PROFIT!  :)
}

Error-checking and optimization left as an exercise to the reader.

like image 141
leppie Avatar answered Dec 04 '22 23:12

leppie


A better way would be to create a type to handle this so you don't have to do all that casting to use the anonymous type.

like image 33
Andrew Hare Avatar answered Dec 05 '22 01:12

Andrew Hare