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.
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).
Haedrian answered this correctly, but i think raw code goes a long ways too. So here's the C# code:
private void CheckedListBox_ItemCheck(Object sender, ItemCheckEventArgs e)
{
int sCount = checkedListBox.CheckedItems.Count;
if (e.NewValue == CheckState.Checked ) { ++sCount; }
if (e.NewValue == CheckState.Unchecked) { --sCount; }
// now sCount is count of selected items in checkedListBox.
}
I had the same issue, and this question and answer gave me the solution. Thanks for the question and already existing answers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With