CheckedListBox data binding to checked state of Items

纵饮孤独 提交于 2019-12-02 05:30:31

Consider these facts:

  1. CheckedListBox does't have a built-in data-binding support for checking items. You need to handle check state of items yourself.

  2. You set checkedListBox1.ValueMember = "Checked";. You didn't set item check state, you just said when you select the item, the value which returns by SelectedValue comes from Checked property of your object which is behind the seected item. For example you can use this code in a Click event of a Button to see the result; regardless of check-state of items, the message box, will show value of Checked property of the object behind the item:

    MessageBox.Show(checkedListBox1.SelectedValue.ToString());
    
  3. Selecting and checking items are completely different.

I prefer to use DataGridView for such purpose. You can simply have a CheckBox column and a readonly TextBox column and bind DataGridView to the list of your objects.

If you need to have two-way data binding, you need to implement INotifyPropertyChanged interface regardless of what control you are using to show data. If you don't implement that interface, when changing properties on your model ListChange event will not raise and you can not see changes in UI automatically.

If you take a look at CheckedListBox class, you'll notice that DataSource, DisplayMember and ValueMember are marked with

[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]

This a common technique used in Windows Forms controls to indicate that some public properties inherited from a base class (hence cannot be removed) are not applicable for that concrete derived class and should not be used.

There must be a reason for doing that for the aforementioned properties of the CheckedListBox. As you already saw, it's "sort of working", but the point is that it isn't guaranteed to work at all. So don't use them. If you wish, create a helper class that holds CheckedListBox and BindingList, listens to ListChanged event and synchronizes the control.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!