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)?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With