[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:

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:

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

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

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Pin It on Pinterest

Share This