Search code examples
c#selectedindexchangedoncheckedchanged

Why is this code not disabling my button after it has been enabled?


I've got a button on a Windows Form that starts off disabled (Enabled = false).

I want to enable it when the user has selected an item from a combobox, and checked at least one item from a CheckedListBox. The user can check/uncheck all the items in the CheckedListBox via a Checkbox, like so:

private void checkBoxAll_CheckedChanged(object sender, EventArgs e)
{
    for (int x = 0; x < MemberListBox.Items.Count; x++)
    {
        MemberListBox.SetItemChecked(x, checkBoxAll.Checked);
    }
    GenPacketBtn.Enabled = MonthAndMemberSelected();
}

So, I thought this would be easy - just check that something has been selected in both the combobox and the CheckedListBox:

private bool MonthAndMemberSelected()
{
    return ((comboBoxMonth.SelectedIndex >= 0) && (MemberListBox.SelectedIndex >= 0));
}

...and then enable or disable the button when these controls are changed, like so:

private void comboBoxMonth_SelectedIndexChanged(object sender, EventArgs e)
{
    GenPacketBtn.Enabled = MonthAndMemberSelected();
}

private void MemberListBox_SelectedIndexChanged(object sender, EventArgs e)
{
    GenPacketBtn.Enabled = MonthAndMemberSelected();
}

Since the checkbox holds so much sway over the CheckedListBox, I added that code to the checkBoxAll_CheckedChanged() event:

private void checkBoxAll_CheckedChanged(object sender, EventArgs e)
{
    for (int x = 0; x < MemberListBox.Items.Count; x++)
    {
        MemberListBox.SetItemChecked(x, checkBoxAll.Checked);
    }
    GenPacketBtn.Enabled = MonthAndMemberSelected();
}

...and (since it didn't work, out of desperation) to its Clicked event, too:

private void checkBoxAll_Click(object sender, EventArgs e)
{
    GenPacketBtn.Enabled = MonthAndMemberSelected();
}

But it doesn't work - enabling the button works, but once it has been enabled, it won't disable again if I uncheck all the items in the CheckedListBox. Why not?


Solution

  • As mentioned in the comments, I think one problem is that you're checking the selected index of the checkedItemBox, rather than validating that no items are checked.

    You could replace the check in MonthAndMemberSelected with something like:

    return ((comboBoxMonth.SelectedIndex >= 0) 
        && (MemberListBox.CheckedItems.Count > 0));
    

    Assuming MemberListBox is your checked item box. This will validate that at least one item is currently checked.

    This may solve your immediate problem, but long term you might want to look into decoupling the validation logic from the UI, as it can get quite complex if there are further fields that rely on each other (may not be worth while if this a small tool to solve a quick problem).