I have a CheckedListBox control and a button in my WinForms project. It contains a list of items, and a max of 5 can be selected. I am using the ItemCheck
event so each time the user checks or unchecks an item in the list a function is called which unchecks the last value if the total number of selected items was more than 5:
private void NumbersListItemChecked(object sender, ItemCheckEventArgs e)
{
CheckedListBox checkedItems = (CheckedListBox)sender;
if (checkedItems.CheckedItems.Count > 4)
{
e.NewValue = CheckState.Unchecked;
}
RefreshButtonState();
}
That way, the number of checked items will never exceed 5.
The button control is supposed to be disabled when the amount of checked items in my CheckedListBox is not 5 and enabled when it is. I am trying to call this function whenever there is a change in state:
private void RefreshButtonState()
{
if (NumbersList.CheckedItems.Count == 5)
{
ModifyButton.Enabled = true;
}
else
{
ModifyButton.Enabled = false;
}
}
However, the button stays disabled even when I have 5 items checked until I try to check a sixth, and vice versa - if I check 5 and then uncheck one, the button will become enabled. I know that this happens because the function is called before the actual change takes place.
Is there an event for CheckedListBox that gets called immediately after there is a state change, not when its about to change?
You don't need another event, just handle the ItemChecked
and use the e.NewValue
to get the count of the checked items after the CheckState
is changed and not when the ItemChecked
event is raised.
private void NumbersListItemChecked(object sender, ItemCheckEventArgs e)
{
var s = sender as CheckedListBox;
var count = s.CheckedIndices.Count + (e.NewValue == CheckState.Checked ? 1 : -1);
if (count > 5)
e.NewValue = CheckState.Unchecked;
ModifyButton.Enabled = count >= 5;
}