我正在尝试做一些非常简单的事情-将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"
。预期产量
人力资源
它
营业额
实际产量
模型部
模型部
模型部
我究竟做错了什么?
最佳答案
您应该更改顺序。
首先设置DataSource
,然后设置DisplayMember
和ValueMember
这应该工作:
clbDepartments.DataSource = departmentSource;
clbDepartments.DisplayMember = "Description";
clbDepartments.ValueMember = "ID";
关于c# - 为什么CheckedListBox DisplayMember不显示?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42052265/