gpt4 book ai didi

c# - 无法将匿名对象转换为 System.Data.DataRowView

转载 作者:行者123 更新时间:2023-11-30 14:37:21 26 4
gpt4 key购买 nike

我使用 linq to sql 来填充 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();
}

稍后在 OnRowDataBound 期间,我调用以下代码来填充单选按钮列表的值

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);
}
}

我收到以下错误:

Unable to cast object of type '<>f__AnonymousType1`3[System.Int32,System.Int16,System.String]' to type 'System.Data.DataRowView'.

我知道不能将匿名对象强制转换为数据行 View ,但是我可以强制转换为什么以获得“which”的值

最佳答案

你应该定义一个适当的类来描述你的数据,然后你就可以转换到这个类。

// replace with proper names and types, as appropriate 
class MyData
{
public int HospId { get; set; }
public string Which { get; set; }
public string Description { get; set; }
}

更新查询的 select利用这个类进行投影

select new MyData
{
HospId = r.hospId,
Which = r.which,
Description = r.description
};

然后使用类型进行转换。

MyData obj = (MyData)(e.Row.DataItem); 
LoadRadioButtonList(obj.Which, rbl);

还有其他技术可以解决这个问题,例如使用 dynamic并让运行时计算出来,或者使用 CastByExample<T>方法(你可以查一下,但我认为它是失败的 hack-ish),但在我看来这是最干净的事情。


你也可以简单地省略投影并使用完整的对象

select r;

此时您只需转换为 db.MyForm1_hosps 中元素的类型,大概是 MyForm1_hosp (你必须验证)。如果您的 UI 容器正在自动生成列并且此类包含比您希望显示的更多的数据,则反对这种方法的方法是,在这种情况下,您会希望继续投影到更小的构造。

关于c# - 无法将匿名对象转换为 System.Data.DataRowView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9335618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com