Which CheckedListBox event triggers after a item is checked?
Solution 1:
You can use the ItemCheck
event, if you also check the new state of the item which is being clicked. This is available in the event args, as e.NewValue
. If NewValue
is checked, include the current item along with the collection proper in your logic:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
List<string> checkedItems = new List<string>();
foreach (var item in checkedListBox1.CheckedItems)
checkedItems.Add(item.ToString());
if (e.NewValue == CheckState.Checked)
checkedItems.Add(checkedListBox1.Items[e.Index].ToString());
else
checkedItems.Remove(checkedListBox1.Items[e.Index].ToString());
foreach (string item in checkedItems)
{
...
}
}
As another example, to determine if the collection will be empty after this item is (un-)checked:
private void ListProjects_ItemCheck(object sender, ItemCheckEventArgs args)
{
if (ListProjects.CheckedItems.Count == 1 && args.NewValue == CheckState.Unchecked)
// The collection is about to be emptied: there's just one item checked, and it's being unchecked at this moment
...
else
// The collection will not be empty once this click is handled
...
}
Solution 2:
There are lots of related StackOverflow posts on this... As well as Branimir's solution, here are two more simple ones:
Delayed execution on ItemCheck (also here):
void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
this.BeginInvoke((MethodInvoker) (
() => Console.WriteLine(checkedListBox1.SelectedItems.Count)));
}
Using the MouseUp event:
void checkedListBox1_MouseUp(object sender, MouseEventArgs e)
{
Console.WriteLine(checkedListBox1.SelectedItems.Count);
}
I prefer the first option, as the second would result in false positives (i.e. firing too often).