简体   繁体   English

c#:如何从linq查询中设置combobox valuemember

[英]c#: how to set combobox valuemember from linq query

ok so i have combobox whos datasource are the results of a linq query 好吧所以我有组合框,而数据源是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";

The problem im having is when i try to add the next line of code 我遇到的问题是当我尝试添加下一行代码时

cboQASupervisor.ValueMember = "ID";

I get an error on runtime that it couldn't cast the anonymous type. 我在运行时遇到错误, 它无法转换匿名类型。 How do i fix this? 我该如何解决?

Correction: The error is: 更正:错误是:

Cannot bind to the new value member. 无法绑定到新值成员。 Parameter name: value 参数名称:value

You specify ID as the value field, but you don't have ID property in your anonymous type. 您将ID指定为值字段,但您的匿名类型中没有ID属性。
Assuming you have ID in your LUT_Employees object: 假设您的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";

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. .ToList()添加到数据源行中的代码中。

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

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