user3596113
user3596113

Reputation: 878

How to disable a button if all CheckedListbox items are unchecked

I want to disable a button if the user unchecks all items in my CheckedListBox. Have a look at my code first:

void checkedListBoxChannels_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        ...

        if (this.checkedListBoxChannels.CheckedItems.Count == 0) {
            this.btnOK.Enabled = false;
        }
        else {
            this.btnOK.Enabled = true;
        }           
    }

The problem now is: When I uncheck the last checkbox and the check in the if block is done the CheckedItems.Count is still 1, so button wont get disabled. Same Problem when I check the first checkbox after no checkbox was checked. The Count is 0 and therefore my button is disabled.

So is there a possibility to find out the currently (after click of the user) checked or unchecked items of the CheckedListBox Control? I searched the EventArgs and sender properties but i couldnt find anything.

thanks for your help

Upvotes: 1

Views: 2066

Answers (4)

user3596113
user3596113

Reputation: 878

Ok i changed my code to:

if (this.checkedListBoxChannels.CheckedItems.Count == 1) {
    if (e.NewValue == CheckState.Unchecked) {
        this.btnOK.Enabled = false;
    }
} else {
    this.btnOK.Enabled = true;
}

now its working fine.

Upvotes: 3

Lev Z
Lev Z

Reputation: 802

You can use NewValue property of ItemCheckEventArgs e:

 private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (checkedListBox1.CheckedItems.Count > 1)
        {
            button1.Enabled = true;
            return;

        }

        //Last Item is uncheked
        if (checkedListBox1.CheckedItems.Count == 1 && e.NewValue == CheckState.Unchecked)
        {
            button1.Enabled = false;
            return;
        }

        //First Item is checked
        if (checkedListBox1.CheckedItems.Count == 0 && e.NewValue == CheckState.Checked)
        {
            button1.Enabled = true;
            return;
        }
    }

Upvotes: 0

Dennis_E
Dennis_E

Reputation: 8894

If you look at the msdn documentation

http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.itemcheck%28v=vs.110%29.aspx

Under 'Remarks' it says: "The check state is not updated until after the ItemCheck event occurs." So it won't register your last change. There are other events you could use. (Click or SelectedIndexChanged maybe?)

Upvotes: 0

Dhaval Patel
Dhaval Patel

Reputation: 7591

your condition should be

this.checkedListBoxChannels.CheckedItems.Count > 0

Upvotes: -1

Related Questions