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!
Mohammad dehghan
source share