[ASP.NET / LINQ] Access GridView DataItem Properties of Anonymous Types
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.
Leave a comment
Follow John Chapman
SharePoint StackExchange
- http://t.co/d2YzH8q1 - #sharepoint - [SharePoint 2010] Specifying Which Server a Custom Timer Job Will Run On
- Always have your stuff when you need it with @Dropbox. 2GB account is free! http://t.co/kczsnniq
- http://t.co/iLWV2Kwp - #sharepoint - [SharePoint 2010] Web Analytics: Monitors the health of the Report Consolidator component
Recent Posts
- [SharePoint 2010] Specifying Which Server a Custom Timer Job Will Run On
- [SharePoint 2010] Web Analytics: Monitors the health of the Report Consolidator component
- [SharePoint 2010 / SQL Server 2008] Query the SharePoint Object Model from a .NET SQL Server CLR Function
- [SharePoint 2010] Debugging a Custom SharePoint Timer Job
- [SharePoint 2010] Set Access Request Email for All SharePoint Sites
