Windows C# CheckedListBox Checked Item Event Handling

rik_davis picture rik_davis · Jul 5, 2010 · Viewed 14.5k times · Source

I'm currently developing a Window app that uses CheckedListBoxes for certain aspects of the program. A problem I've encountered is that I have been trying to find which event is triggered when an item is checked so that I can enable a form button when any list item is checked.

Problem is that I tried using the following;

private void clbAvailMods_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if(e.NewValue == CheckState.Checked)
        {
            btnInstall.Enabled = true;
        }
    }

but when I set a breakpoint on the if statement, it never fires upon checking an item in the listbox.

Am I doing something wrong here?

Answer

Hans Passant picture Hans Passant · Jul 5, 2010

A standard Windows Forms trick is to delay running code until all event side-effects have been completed. You delay running code with the Control.BeginInvoke() method. This will fix your problem:

    private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e) {
        this.BeginInvoke(new MethodInvoker(evalList), null);
    }

    private void evalList() {
        bool any = false;
        for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix) {
            if (checkedListBox1.GetItemChecked(ix)) {
                any = true;
                break;
            }
        }
        btnInstall.Enabled = any;
    }