CheckedListBox data binding to checked state of Items

前端 未结 2 1077
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-25 02:52

I tried to set DataSource of CheckedListBox like this:

private void Form1_Load(object sender, EventArgs e)
    {
        checkedListBox1.DisplayMember = \"Name\"         


        
相关标签:
2条回答
  • 2021-01-25 03:32

    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.

    0 讨论(0)
  • 2021-01-25 03:43

    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.

    0 讨论(0)
提交回复
热议问题