简体   繁体   中英

c#: how to set combobox valuemember from linq query

ok so i have combobox whos datasource are the results of a linq query

//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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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