Reputation: 103
In my windows forms project written in C# I try to clear a CheckedListBox after the last Item is checked.
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (checkedListBox1.CheckedItems.Count + 1 == checkedListBox1.Items.Count)
{
checkedListBox1.Items.Clear();
}
}
In this example, the program would throw a NullReferenceException, after I check the last item.
Could somebody explain why this is happening and how I can handle this?
Thanks in advance!
Upvotes: 2
Views: 4433
Reputation: 125312
Change your code to run the logic after the check state of the item updated:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
checkedListBox1.BeginInvoke(new Action(() =>
{
if (checkedListBox1.CheckedItems.Count == checkedListBox1.Items.Count)
{
checkedListBox1.Items.Clear();
}
}));
}
According to the documentations, by default, when the ItemCheck
event raises, the check state of the item is not updated until after the ItemCheck
event occurs. It means it tries to update the check state of the item after running the code that you have in the event handler. As a result in your code, it tries to update item check state after the item removed from items collection and that's why an exception happens. You can see what happens in stack trace, also in source code of the control.
In above code, using BeginInvoke
we delay running the code after the check state is updated. You can read more about it in this post.
Upvotes: 5
Reputation: 13003
It is because after you clear the items from the checklistbox
, there is some internal call (System.Windows.Forms.CheckedListBox.CheckedItemCollection.SetCheckedState
) that is invoked later and still operates on the items. So it throws the NullReferenceException
.
If you register the SelectedIndexChanged
event instead, you can clear the items without having this problem.
The difference is the timing, ItemCheck
is triggerred early, at that time you can't clear the items, and SelectedIndexChanged
is triggered much later.
Upvotes: 1