为什么CheckedListBox DisplayMember不显示?

时间:2017-02-05 12:51:01

标签: c# winforms

我正在尝试做一些非常简单的事情 - 将CheckedListBox绑定到对象列表。

  

课程定义

namespace Models
{
    public class Department
    {
        public int ID { get; set; }
        public string Description { get; set; }
    }
}
  

复制问题的最小完整代码示例

     

(首先创建CheckedListBox clbDepartments)

    private void Form1_Load(object sender, EventArgs e)
    {
        List<Department> departmentList = new List<Department>();
        departmentList.Add(new Department { ID = 1, Description = "HR" });
        departmentList.Add(new Department { ID = 2, Description = "IT" });
        departmentList.Add(new Department { ID = 3, Description = "Sales" });

        var departmentBindingList = new BindingList<Department>(departmentList);
        var departmentSource = new BindingSource(departmentBindingList, null);
        clbDepartments.DisplayMember = "Description";
        clbDepartments.ValueMember = "ID";
        clbDepartments.DataSource = departmentSource;
    }

列表绑定 - 我可以在CheckboxList中的每个项目List<Department>中看到一个项目。

但是,不是显示"Description"字段DisplayMember的值,而是显示每个项目的"Models.Department"

  

预期输出

     

HR

     

IT

     

销售

  

实际输出

     

Models.Department

     

Models.Department

     

Models.Department

我做错了什么?

1 个答案:

答案 0 :(得分:5)

您应该更改订单 首先设置DataSource,然后设置DisplayMemberValueMember

这应该有效:

clbDepartments.DataSource = departmentSource;
clbDepartments.DisplayMember = "Description";
clbDepartments.ValueMember = "ID";