CheckedListBox binding update DataSource

992 Views Asked by At

Here is my code. I want to update the DataSource when user check/uncheck an item in the CheckedListBox. But when I dump the data source, nothing has been changed. Why?

BindingSource source = new BindingSource();

IList<MyStr> list = new List<MyStr>();
list.Add(new MyStr() { Index = 0, Name = "A", Checked = false });
list.Add(new MyStr() { Index = 1, Name = "B", Checked = false });
list.Add(new MyStr() { Index = 2, Name = "C", Checked = true });
list.Add(new MyStr() { Index = 3, Name = "D", Checked = false });
list.Add(new MyStr() { Index = 4, Name = "E", Checked = false });

source.DataSource = list;

((ListBox)this.cbList).DataSource = source;
((ListBox)this.cbList).DisplayMember = "Name";
((ListBox)this.cbList).ValueMember = "Checked";

public class MyStr
{
    public int Index { get; set; }
    public String Name { get; set; }
    public bool Checked { get; set; }

}
1

There are 1 best solutions below

2
On

Unfortunately, the CheckedListBox does not support that functionality, which is why the DataSource properties were hidden from you in the designer.

You would have to do the plumbing yourself:

((ListBox)this.cbList).DataSource = source;
((ListBox)this.cbList).DisplayMember = "Name";
((ListBox)this.cbList).ValueMember = "Checked";
for (int i = 0; i < list.Count; ++i) {
  cbList.SetItemChecked(i, list[i].Checked);
}
this.cbList.ItemCheck += (sender, e) => {
  list[e.Index].Checked = (e.NewValue != CheckState.Unchecked);
};