TinyRacoon
TinyRacoon

Reputation: 4903

C# How do you add a "Select All" option to a CheckedListBox that works like the "Select All" option in MS Excel

In MS Excel when you use a filter on your data there is a "(Select All)" option.

enter image description here

How do you do that in C# with Forms and using a CheckedListBox control?

Required behaviour:

  1. "(Select All)" is first in the list.
  2. When "(Select All)" is checked, all other items are set to checked. And vice versa for unchecked.

(N.B. I'm answering my own question because I've spent far too long working out this solution and thought it might save someone else the time :)

Upvotes: 1

Views: 914

Answers (1)

TinyRacoon
TinyRacoon

Reputation: 4903

Here is code that does as requested.

public partial class Form1 : Form
{
    private static string txtSelectALL = "(Select all)";

    public Form1()
    {
        InitializeComponent();

        checkedListBox1.Items.Add(txtSelectALL);
        checkedListBox1.Items.Add("Matt");
        checkedListBox1.Items.Add("Chris");
        checkedListBox1.Items.Add("Dominic");
    }

    private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        // If nothing is changing, do nothing...
        if (e.NewValue == e.CurrentValue) { return; }
        
        // If this is NOT the "Select All" item...
        if (checkedListBox1.Items[e.Index].ToString() != txtSelectALL) { return; }
        
        // It is the "Select All" item, so whatever CheckState that is changing to, 
        // we want to do the same to all the other items...
        for (int iItem = 0; iItem < checkedListBox1.Items.Count; iItem++)
        {
            // Must skip the item that was changing already (else we get a recursive loop)...
            if (iItem == e.Index) { continue; }

            checkedListBox1.SetItemCheckState(iItem, e.NewValue);
        }
    }
}

And it looks like this:

enter image description here

Upvotes: 4

Related Questions