I use to linq to sql to fill a gridview:
var results = from r in db.MyForm1_hosps
where r.recordId == recordId
orderby r.hospId
select new { r.hospId, r.which, r.description };
if (results.Count() > 0)
{
Form_1_hosp.DataSource = results;
Form_1_hosp.DataBind();
}
later during OnRowDataBound, i call the following code to fill in the value of a radiobuttonlist
if (e.Row.RowType == DataControlRowType.DataRow)
{
RadioButtonList rbl = e.Row.FindControl("which") as RadioButtonList;
if (rbl != null)
{
DataRowView rowView = (DataRowView)(e.Row.DataItem);
LoadRadioButtonList(rowView["which"], rbl);
}
}
I get the following error:
Unable to cast object of type '<>f__AnonymousType1`3[System.Int32,System.Int16,System.String]' to type 'System.Data.DataRowView'.
I understand that an anonymous object cannot be cast to a datarowview, but what can I cast to in order to get the value of “which”
You should define a proper class to describe your data, and then you will be able to cast to this class.
Update your query’s
selectto utilize this class for the projectionAnd then use the type for the cast.
There are other techniques for dealing with this, such as using
dynamicand letting the runtime figure it out, or using aCastByExample<T>method (you can look it up, but I consider it faily hack-ish), but this is in my opinion the cleanest thing to do.You could arguably also simply omit the projection and use the full object
At which point you would simply cast to the type of the elements in
db.MyForm1_hosps, which is presumablyMyForm1_hosp(you would have to verify). The counter against this approach would be if your UI container is auto-generating columns and this class contains more data than you wish to display, in which case, you would want to continue with the projection into a smaller construct.