开发者

c#: how to set combobox valuemember from linq query

开发者 https://www.devze.com 2023-03-06 11:40 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消