C#:如何从LINQ查询设置ComboBox ValueMember
-
14-11-2019 - |
题
好,所以我有combobox whos dataSource是LINQ查询的结果
//load QA names
var qaNames =
from a in db.LUT_Employees
where a.position == "Supervisor" && a.department == "Quality Assurance"
select new { a, Names = a.lastName + ", " + a.firstName };
cboQASupervisor.DataSource = qaNames;
cboQASupervisor.DisplayMember = "Names";
.
问题我是时候尝试添加下一行代码
cboQASupervisor.ValueMember = "ID";
.
我在运行时收到错误,即它无法施放匿名类型。如何修复这个?
更正: 错误是:
不能绑定到新值成员。 参数名称:值
解决方案
You specify ID as the value field, but you don't have ID property in your anonymous type.
Assuming you have ID in your LUT_Employees object:
var qaNames = (
from a in db.LUT_Employees
where a.position == "Supervisor" && a.department == "Quality Assurance"
select new { a.ID, Names = a.lastName + ", " + a.firstName })
.ToList();
cboQASupervisor.DataSource = qaNames;
cboQASupervisor.DisplayMember = "Names";
cboQASupervisor.ValueMember = "ID";
其他提示
You can try this:
var qaNames =
from a in db.LUT_Employees
where a.position == "Supervisor" && a.department == "Quality Assurance"
select new { Id = a.ID, Names = a.lastName + ", " + a.firstName };
cboQASupervisor.DataSource = qaNames.ToList();
cboQASupervisor.DisplayMember = "Names";
cboQASupervisor.ValueMember = "Id";
Add .ToList()
to your code in the datasource line.
不隶属于 StackOverflow