Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CheckedListBox checked list item property binding to field in a class

I have a class with two properties and I want to bind it to a CheckedListBox item. WebsiteName property will be the DisplayValue and IsChecked should be the Checked state of the item :

public class ACLASS:
{       
    public string WebsiteName 
    { 
        get;
        set;
    }

    public bool IsChecked
    {
        get;
        set;
    }

    public ACLASS() 
    {

    }
}

This is how I 'try' to bind it:

    ACLASS aclass = new ACLASS();
    aclass.WebsiteName = "www.example.com";
    BindingList<ACLASS> list = new BindingList<ACLASS>();
    list.Add(aclass);

    checkedlistbox.DataSource    = list;
    checkedlistbox.DisplayMember = "WebsiteName";       

This is all fine and works but how do I also bind the Checked state of the items in the CheckedListBox with the IsChecked property of the class so when I check a item in the CheckedListBox it will also change the IsChecked property of the ACLASS instance? I need this so I can verify the checked state of the item through the ACLASS instance.

like image 654
kawa Avatar asked May 30 '14 16:05

kawa


1 Answers

The CheckedListBox control doesn't really support a DataSource, which is why the designers hid it from Intellisense. You can use it, but the checkmark property of the listbox won't work with your class, even if you set the ValueMember property to your boolean property.

Unfortunately, it means you have to set the values yourself:

checkedlistbox.DataSource = list;
checkedlistbox.DisplayMember = "WebsiteName";
for (int i = 0; i < checkedListbox.Items.Count; ++i) {
  checkedListbox.SetItemChecked(i, ((ACLASS)checkedListbox.Items[i]).IsChecked);
}

and you also have to track the changes yourself, too:

checkedListBox1.ItemCheck += (sender, e) => {
  list[e.Index].IsChecked = (e.NewValue != CheckState.Unchecked);
};
like image 71
LarsTech Avatar answered Sep 19 '22 09:09

LarsTech