I'm trying to do something very simple - bind a CheckedListBox to a list of objects.
Class definition
namespace Models
{
public class Department
{
public int ID { get; set; }
public string Description { get; set; }
}
}
Minimal complete code sample to replicate the issue
(Create CheckedListBox clbDepartments first)
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;
}
The list binds - I can see one item in the CheckboxList per item in the List<Department>.
But instead of displaying the value of the "Description" field, which is the DisplayMember, the list displays "Models.Department" for each item.
Expected Output
HR
IT
Sales
Actual Output
Models.Department
Models.Department
Models.Department
What am I doing wrong?
You should change the order.
First set the DataSource and then set the DisplayMember and ValueMember
This should work:
clbDepartments.DataSource = departmentSource;
clbDepartments.DisplayMember = "Description";
clbDepartments.ValueMember = "ID";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With