繁体   English   中英

将控件绑定到LINQ查询-找不到字段

[英]Binding controls to LINQ queries - cannot find field

我有几个试图绑定到LINQ查询的控件,但出现以下错误:

$ exception {“ DataBinding:'System.Data.DataRow'不包含名称为'Key'的属性。”} System.Exception {System.Web.HttpException}

我通过以下方式绑定它:

    myDropDownList.DataSource = myDataTable.AsEnumerable().Where(
                        r => ((string) r["ColumnName"]) == "ColumnIWant").ToList()
myDropDownList.DataTextField = "Key";
myDropDownList.DataValueField = "Value";

正如其他答案中所建议的那样,无论是否有.ToList(),我都尝试过此操作,但没有任何效果。

"myDataTable"具有列"Key""Value" 据我了解,您可以通过这种方式进行绑定,但是我似乎缺少指定属性名称的步骤。

我的建议(因为它已经对GridView和DropDownList控件DataTextField ),是您在设计文件(aspx)中指定此DataTextFieldDataValueField属性,如下所示:

<asp:DropDownList ID="DropDownList1" runat="server" 
                  DataTextField="Key" DataValueField="Value">
</asp:DropDownList>

这样,您仍然可以将ToList()函数应用于DataTable,它将起作用(经过测试)。

如果不是,则可能需要在填满myDataTable之后设置一个断点,然后在LINQ查询之后设置另一个断点,以检查“ Key”和“ Value”列是否仍然存在。

如果它在数据表中明确包含keyValue ,那么我建议您使用如下所示:

myDropDownList.DataSource = myDataTable.AsEnumerable().Where(
                    r => (r.Field<string>("ColumnName")) == "ColumnIWant").ToList<DataRow>();
myDropDownList.DataTextField = "Key";
myDropDownList.DataValueField = "Value";

我已经将ToList()更改为.ToList<DataRow>(); 这样数据源就可以从数据表中找到keyvalue ,并像这样更改比较: r.Field<string>("ColumnName")

使用.CopyToDataTable()可以达到我想要的目的,但是我仍然更愿意知道如何将数据直接绑定到EnumerableRows集合。

这是我所做的:

myDropDownList.DataSource = myDataTable.AsEnumerable().Where(
                        r => ((string) r["ColumnName"]) == "ColumnIWant").CopyToDataTable();
myDropDownList.DataTextField = "Key";
myDropDownList.DataValueField = "Value"; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM