Search code examples
c#loopscheckboxcheckedlistbox

C# Check All from a CheckedListBox without showing the "Check All" entry


I have a small program that has several checkedboxlists in VS2010. I wanted to allow a user to select all in one of the lists and came up with this looping structure...

private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (e.NewValue == CheckState.Checked)
        {
            Applications.Add(CheckedListBox1.Items[e.Index].ToString());
        }
        else if (e.NewValue == CheckState.Unchecked)
        {
            Applications.Remove(CheckedListBox1.Items[e.Index].ToString());
        } 
    }

private void CheckedListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (CheckedListBox1.SelectedIndex == 0)
        {
            for (int i = 1; i < CheckedListBox1.Items.Count; i++)
            {
                CheckedListBox1.SetItemChecked(i, CheckedListBox1.GetItemChecked(0));
            }
        }
        else
        {
            if (!CheckedListBox1.GetItemChecked(CheckedListBox1.SelectedIndex))
            {
                CheckedListBox1.SetItemChecked(0, false);
            }
        }

    }

The problem is this also puts the "Select All" checkbox into the output. Is there a way I can tweak the loop to not include the first checkbox (which is the "Select All" Check) or should I be going about this a different way?


Solution

  • Pretty unclear what "into the output" might mean. Using the SelectedIndexChanged event isn't very appropriate, the ItemCheck event signals checking an item. Try this instead:

        private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
            if (e.Index == 0) {
                for (int item = 1; item < checkedListBox1.Items.Count; item++) {
                    checkedListBox1.SetItemChecked(item, true);
                }
                e.NewValue = CheckState.Unchecked;  // Prevent "Check All" from getting checked
            }
        }
    

    If you want to use SelectedIndexChanged anyway then still keep this event handler to prevent the item from getting checked.