Title: Display the number of checked items in a CheckedListBox in C#
The CheckedListBox control has a CheckedItems collection that holds references to the control's currently checked items. You can use the collection's Count property to determine the number of items checked.
When the user checks or unchecks an item, the control raises its ItemCheck event to let you know. Unfortunately the control's CheckedItems collection has not yet been updated so the collection's Count does not give you the value it will have after the item is checked or unchecked.
To display an accurate count, you need to look at the event handler's e.CurrentValue and e.NewValue parameters to determine whether the item should be included in the count.
When you check and uncheck items in this example, the following ItemCheck event handler displays the total number of checked items in the CheckedListBox and the total number of items in the list.
// Update the display of files checked.
private void clbFiles_ItemCheck(object sender, ItemCheckEventArgs e)
{
// Get the current number checked.
int num_checked = clbFiles.CheckedItems.Count;
// See if the item is being checked or unchecked.
if ((e.CurrentValue != CheckState.Checked) &&
(e.NewValue == CheckState.Checked))
num_checked++;
if ((e.CurrentValue == CheckState.Checked) &&
(e.NewValue != CheckState.Checked))
num_checked--;
// Display the count.
lblCount.Text = clbFiles.Items.Count + " items, " +
num_checked + " selected";
}
The code gets the current number of items checked. Then depending on the e.CurrentValue and e.NewValue parameters, it updates that count. The event handler finishes by displaying the total number of items and the number of checked items.
This example demonstrates one other useful technique for using CheckedListBox controls. Normally you must select an item in the list to give it focus and then click its box to check it. That means you need to click the item twice to check or uncheck it, which seems pretty awkward.
You can make this easier and less annoying if you set the control's CheckOnClick propertry to true. Then when the user clicks an item in the list, it is immediately checked or unchecked.
This example's Form_Load event handler uses the following statement to set this property (or you can do it at design time).
clbFiles.CheckOnClick = true;
Download the example to experiment with it and to see additional details.
|