How to track checks in checkListBox C #?

I am trying to display the number of checked items in checkedListBox: checkedListBox1.CheckedIndices.Count But how can I update my account if I want to display it on a shortcut? I tried to write everything in the ItemCheck event:

 private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) { label1.Text= checkedListBox1.CheckedIndices.Count; } 

But the score increases, even if I uncheck :( I would be grateful for any help!

+7
source share
3 answers

Just add one or subtract one depending on e.NewValue==CheckState.Checked

+1
source

The documentation for the CheckedListBox.ItemCheck event states that:

Validation status is not updated until the ItemCheck event occurs.

therefore, when an event is CheckedIndices.Count , CheckedIndices.Count is not yet updated. To overcome this, you must subclass the CheckedListBox class and fire a new event after the CheckedListBox.ItemCheck event:

 public class MyCheckedListBox : CheckedListBox { public event ItemCheckEventHandler ItemCheckedChanged; protected virtual void OnItemCheckedChanged(ItemCheckEventArgs ice) { var h = ItemCheckedChanged; if (h != null) h(this, ice); } protected override void OnItemCheck(ItemCheckEventArgs ice) { base.OnItemCheck(ice); ThreadPool.QueueUserWorkItem(new WaitCallback((state) => { this.BeginInvoke(new Action<ItemCheckEventArgs>(OnItemCheckedChanged), ice); })); } 

No, you have an ItemCheckedChanged event that you can subscribe to.

In fact, there is no need for a subclass. It can be done in the form itself, but it is cleaner.

How it works?

The ItemCheck event ItemCheck raised inside the SetItemCheckState method. This method changes the check state of an element after an event is called ( OnItemCheck ). Also, the SetItemCheck call is the result of a Windows message that is passed to the application message queue. We want our message to be launched after processing this message, so we must send a new message to the queue so that our message is processed after this message. The BeginInvoke method actually sends a message to the message queue, but only when called from another thread. Therefore, I called BeginInvoke in the thread pool of the new threads.

Another solution for this would be to register the message and send it manually to the message queue, but that will be a lot more code!

+3
source

Rather do the following:

 int checkedcount = 0; foreach(var item in checkedListBox1.CheckedItems){ if(checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(item) == System.Windows.Forms.CheckState.Checked) checkedcount++; } 

See here for more help.

0
source

All Articles