Wednesday, March 13, 2013

LinqDataSource Bound Grid View and RowDataBound Handling

Scenario

You have bound a LinqDataSource to DataGridView.

Now you want to dynamically modify the contents of grids using RawDataBound event based on the row data, for example flag a field as RED when there is an overdue account, but you do not know how to get to the data contained in Row.DataItem

You will quickly find that DataItem is a member of DynamicClass for which there is no public property to methods to get to the data. You will also find that your debugger can display the information, and it just a row from a LINQ select statement.

Solution

A very small amount of Reflection is needed to do this work. Suppose that you had a column in the table in the LinqDataSource with the name of "CustomerGuidKey". Here is how to get at it.

   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        var item = e.Row.DataItem;
        if (item == null) return;
        var t = item.GetType();
        PropertyInfo p = t.GetProperty("CustomerGuidKey");
        var v = (Guid) p.GetValue(item, null);
.....

Be sure to include the namespace "System.Reflection" in your code.


Post a Comment