[英]Bind LINQ Result to DataGrid
我有想要绑定到DataGrid
的 Linq 结果,所以我可以编辑结果。 请告知我做错了什么。 以下是我的C#
代码:
var root = XElement.Parse(xmlText);
var elementsThatCanBeEmpty = new HashSet<XName>
{
XName.Get("Login"),
XName.Get("CustomerStreet2"),
XName.Get("PayeeStreet2"),
XName.Get("PayAsName"),
XName.Get("PayeeAccount")
};
var transactionList =
from transactions in root.Elements(XName.Get("Transactions")).Elements().AsEnumerable()
where transactions.Elements().Any
(
el =>
String.IsNullOrEmpty(el.Value) &&
!elementsThatCanBeEmpty.Contains(el.Name)
)
select transactions;
foreach (var t in transactionList)
{
Response.Write(t.Element(XName.Get("CustomerName")).Value);
}
dgBillPay.DataSource = transactionList;
dgBillPay.DataBind();
当我运行该页面时,DataGrid 的标题为“ Value
、 Xml
、 HasAttributes
、 HasElements
、 IsEmpty
、 Value
、 BaseUri
”。 我在这里做错了什么? 请指教。
通常,asp.net 控件中的数据绑定通过检查作为数据源提供的对象列表的属性来工作。
在这种情况下,数据网格已设置为自动生成列,这意味着它将根据传递给它的对象的属性自动生成标题。 在这里,您传递了一个IEnumerable<XElement>
,因此它使用其属性列表作为绑定列表。
您的选择是:
匿名类型可能是这里阻力最小的路径。
我相信您看到的问题是因为您在将查询结果绑定到控件之前已经枚举了它们。
foreach (var t in transactionList)
{
Response.Write(t.Element(XName.Get("CustomerName")).Value);
}
一旦执行了该语句,我很确定 transactionList 不能用于其他任何事情,除非再次执行查询。
要尝试的另一件事是通过在查询上调用 ToList() 将 transactionList 查询结果转换为列表。
试试这两件事,看看会发生什么。
从代码的外观来看; 您似乎根据 LINQ 查询将 XmlElements 集合绑定到 DataGrid。
我想你可能想要这样的东西:
var transactionList =
from transactions in root.Elements(XName.Get("Transactions")).Elements().AsEnumerable()
where transactions.Elements().Any
(
el =>
String.IsNullOrEmpty(el.Value) &&
!elementsThatCanBeEmpty.Contains(el.Name)
)
select new { CustomerName = transactions.Element(XName.Get("CustomerName")).Value};
然后按照您认为合适的方式填写 select 部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.