C# 将Linq绑定到Datagridtextcolumn
我想从Linq查询向DatagridTextcolumn添加值 我所尝试的:C# 将Linq绑定到Datagridtextcolumn,c#,wpf,linq,linq-to-sql,C#,Wpf,Linq,Linq To Sql,我想从Linq查询向DatagridTextcolumn添加值 我所尝试的: DataGridTextColumn test = new DataGridTextColumn(); test.Binding = new Binding("test"); dgServer.Columns.Add(test); dgServer.Items.Add(new Person() { Status = Convert.ToBoolean(from a in db.Persons
DataGridTextColumn test = new DataGridTextColumn();
test.Binding = new Binding("test");
dgServer.Columns.Add(test);
dgServer.Items.Add(new Person()
{
Status = Convert.ToBoolean(from a in db.Persons
from d in db.PersonDetails
where a.pID == d.pDID && a.State == "Active"
select a)
});
XAML
我对上述代码有一个例外,即
无法将“System.Data.Objects.ObjectQuery”1类型的对象强制转换为“System.IConvertible”类型
如何绑定到从LINQ到SQL的DatagridTextcolumn
绑定
请帮助这是有问题的代码-
Status = Convert.ToBoolean(from a in db.Persons
from d in db.PersonDetails
where a.pID == d.pDID && a.State == "Active"
select a)
内部的查询将返回Person类型的
IEnumerable
,您正试图将其转换为Boolean
,这显然无法编译,因为没有从IEnumerable
到Boolean
的隐式转换,问题是您试图转换的是linq查询,而不是该查询的结果。这个问题源于Linq的延迟执行模型。尝试将“FirstOrDefault()”方法添加到ToBoolean调用的参数中:
Status = Convert.ToBoolean((from a in db.Persons
from d in db.PersonDetails
where a.pID == d.pDID && a.State == "Active"
select a).FirstOrDefault())
Rohit也有一个很好的观点-您需要确保能够从Person类型转换为Boolean类型感谢更新,但是如何将其绑定到DatagridTextcolumn绑定属性?@Buba1947记住这个答案将是
,因此您忘记了路径。
Status = Convert.ToBoolean((from a in db.Persons
from d in db.PersonDetails
where a.pID == d.pDID && a.State == "Active"
select a).FirstOrDefault())