简体   繁体   中英

CheckedListBox event *after* CheckState changed

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;
}

Use ItemCheck event and check new state of the item which was checked. New state is in event arg as e.NewValue. You can than check state in if(e.NewValue== CheckState.Check) and use it in your logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM