How to count only checked items in CheckedListBox dynamically while the user is checking boxes?

Indigo picture Indigo · Oct 25, 2012 · Viewed 22.5k times · Source

I have a CheckedListBox control on my windows form application, which gives a list of items to select from. I want to count and show only checked (not selected) items while the user is still checking them. I mean count as you check them.

I have tried to use ItemCheck event and CheckedListBox.CheckedItems.Count but the problem is that it counts every other click even if the item is unchecked. When I check something it counts and if I unchecked it again, it counts that too.

I think it has to do with the remark given on MSDN "The check state is not updated until after the ItemCheck event occurs." I do not completely understand the problem here.

Thank you.

Answer

Haedrian picture Haedrian · Oct 25, 2012

The ItemCheckEventArgs parameter has the Property (NewValue) which tells you whether the change is a check, uncheck or neither.

If CheckedItems.Count is not updated until after the event fires (which is what I'm understanding from that remark) - then you can add that count, and see whether the ItemChecckEventArgs is a check (+1) or an uncheck (-1) and you can get the correct total.

(Unless I'm understanding the remark wrongly, its very vague).