How can I immediately/reactively determine if any

2019-07-28 02:14发布

问题:

This question already has an answer here:

  • No ItemChecked event in a CheckedListBox? 4 answers

I want to enable a button only if valid criteria have first been selected (C# Windows Forms app). I have this code (I tried the IndexChanged and ValueChanged events first, but this answer indicates the ItemCheck event is the one to monitor:

private void checkedListBoxUnits_ItemCheck(object sender, ItemCheckEventArgs iceargs)
{
    buttonGenRpts.Enabled = ValidSelections();
}

private bool ValidSelections()
{
    bool OneUnitSelected = checkedListBoxUnits.CheckedItems.Count == 1;
    . . .

OneUnitSelected is always false, even after selecting an item (checkbox control) in the checkedListBoxUnits control. It seems that these events fire before the checkbox is actually checked. So what event can I tap into to verify an item has been checked in a CheckedListBox?

回答1:

This is a bit hacky, but you could defer running ValidSelections until the checking is complete:

private void checkedListBoxUnits_ItemCheck(object sender, ItemCheckEventArgs iceargs)
{
    BeginInvoke(() => {
        buttonGenRpts.Enabled = ValidSelections();
    });
}