I tend to use LINQ for just about everything I can. Many times this involves populating ASP.NET GridViews from code with anonymous types from LINQ. For example:

[csharp]var linqQuery = from p in context.Table
select new
{
ID = p.Id,
Name = p.LastName + “, ” + p.FirstName,
HireDate
};

gridView.DataSource = linqQuery;
gridView.DataBind();[/csharp]

The issue that I came across is that when I need to access data from that query during an OnRowDataBound event. When trying to access the item using the following code I would get error about casting anonymous types to DataRowView:

[csharp]//This doesn’t work
var row = (DataRowView) e.Row.DataItem;
var value = row[“HireDate”].ToString();[/csharp]

Using the suggestion from this Stack Overflow answer I was able to retrieve the value by reflecting the anonymous type:

[csharp]protected void gridView_RowDataBound(object sender, GridViewEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow) return;

DateTime? hireDate = null;

var row = e.Row.DataTime;
var type = row.GetType();
var property = type.GetProperty(“HireDate”);
if (property != null && property.PropertyType == typeof(DateTime?))
hireDate = property.GetValue(row, null) as DateTime?;

// Voila – hireDate now has a value, now I can do something with it
}[/csharp]

I’m sure there is a more efficient way to do this, however this works for me. Hopefully you find it useful too.


Pin It on Pinterest

Share This
%d bloggers like this: