Monday, August 1, 2011

Linq and RowDataBound

I used to get values of databound row by casting e.Row.DataItem to DataRowView.
var row = (DataRowView)e.Row.DataItem;

And get values using something like this
var myValue = DataRowView["ExampleColumnName"];

Btw, it's better to cast to typed datarow, in case, typed datatable is used as datasource.
var row = (ExampleDataSet.ExampledataRow)((DataRowView) e.Row.DataItem).Row;
var myValue = row.ExampleColumnName;

But recently, i encountered obstacle to obtain values, when linq query acts as datasource. Then e.Row.DataItem is anonymous type, and no way to cast it to something reasonable.

Hopefully, the old method still exists, and it's working fine with linq:
var myValue = DataBinder.Eval(e.Row.DataItem, "ExampleColumnName");