[ASP.NET / LINQ] Access GridView DataItem Properties of Anonymous Types

+1Share on TwitterShare on FacebookShare on LinkedInSubmit to StumbleUponhttp://d32vechvmk8aon.cloudfront.net/wp-content/uploads/2012/09/spjohnscreenshot.jpegDigg ThisSubmit to redditPin it on Pinterest

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:

var linqQuery = from p in context.Table
	select new
	{
		ID = p.Id,
		Name = p.LastName + ", " + p.FirstName,
		HireDate
	};

gridView.DataSource = linqQuery;
gridView.DataBind();

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:

//This doesn't work
var row = (DataRowView) e.Row.DataItem;
var value = row["HireDate"].ToString();

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

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
}

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

John Chapman

Hello, I'm John Chapman. I am a SharePoint Developer for NewsGator living in Denver, Colorado. I develop solutions using ASP.NET, C#, jQuery, SQL, SharePoint, etc, and I thrive on the challenge of writing code to overcome the impossible, annoying, or otherwise difficult obstacles.

More Posts - Website - Twitter - LinkedIn - Google Plus