Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 962
Sinaesthetic Avatar asked May 18 '11 03:05

Sinaesthetic


2 Answers

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";
like image 181
Alex Aza Avatar answered Nov 06 '22 07:11

Alex Aza


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.

like image 22
Peyton Crow Avatar answered Nov 06 '22 07:11

Peyton Crow