C#:如何从 LINQ 查询设置 Combobox ValueMember



好的,所以我有组合框谁的数据源是 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";

我在运行时收到一个错误,它无法强制转换匿名类型。我该如何解决这个问题?

校正:错误是:

无法绑定到新的值成员。 参数名称:值

指定 ID

作为值字段,但匿名类型中没有 ID 属性。
假设您的 LUT_Employees 对象中有 ID:

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";

你可以试试这个:

       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";

.ToList()添加到数据源行中的代码中。

相关内容

  • 没有找到相关文章

最新更新