Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 780
Indigo Avatar asked Dec 01 '22 05:12

Indigo


2 Answers

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).

like image 89
Haedrian Avatar answered Dec 05 '22 03:12

Haedrian


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!

like image 24
Shawn Kovac Avatar answered Dec 05 '22 03:12

Shawn Kovac