3

I am trying to bind a label to a CheckedListBox.CheckedItems.Count I have tried a couple approaches to this and receive the message:

Cannot bind to the property or column Count on the DataSource. Parameter name: dataMember

My Code is as Follows:

    Dim BgCountBinding As Binding = New Binding("Text", BgCheckedListBox.CheckedItems, "Count")

  ' I have also tried this:     
  ' Dim BgCountBinding As Binding = New Binding("Text", BgCheckedListBox, "CheckedItems.Count")

    BgCountBinding.DataSourceUpdateMode = DataSourceUpdateMode.Never
    BgCountBinding.ControlUpdateMode = ControlUpdateMode.OnPropertyChanged
    BgCountBinding.NullValue = "0"
    BgCountBinding.FormattingEnabled = True
    BgCountBinding.FormatString = "#: {0}"


    lblBGCount.DataBindings.Add(BgCountBinding)

I know the code is VB but if you have a C# version - I can and will be happy to convert it.

Ken
  • 2,518
  • 2
  • 27
  • 35

1 Answers1

3

Since the CheckListBox doesn't support multi-selection, probably you mean CheckItems.Count. You can not bind to CheckItems.Count. To be notified about changing in CheckedItem.Count you should handle ItemCheck event of the CheckedListBox:

C#

this.checkedListBox1.ItemCheck += (s, ea) =>
{
    this.BeginInvoke(new Action(() =>
    {
        this.label1.Text = this.checkedListBox1.CheckedItems.Count.ToString();
    }));
};
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • The ItemCheck event does not show CheckedItems.Count - it does not update that value until After the event. I know I can get e.newValue - I do not want that , I want the actual count - not 1 off. Which is why I wanted to go the binding route. In my searching it does not seem this is possible. – Ken Sep 29 '16 at 15:50
  • *The check state is not updated until after the ItemCheck event occurs.*. See the edit, also [this post](http://stackoverflow.com/questions/32291324/manage-checkedlistbox-itemcheck-event-to-run-after-an-item-checked-not-before). The key point is using `BeginInvoke` to ask for count of items. This way, the count of items after ckecking/unchecking will be returned to you. – Reza Aghaei Sep 29 '16 at 15:57
  • Yes I was reading this post : http://stackoverflow.com/questions/3181985/windows-c-sharp-checkedlistbox-checked-item-event-handling I am testing it now. – Ken Sep 29 '16 at 16:14
  • Just use above code. You don't need to handle `SelectedIndexChanged`. Using `ItemCheck` is enough! You just need to use `BeginInvoke`. – Reza Aghaei Sep 29 '16 at 16:16