Reputation: 4903
In MS Excel when you use a filter on your data there is a "(Select All)" option.
How do you do that in C# with Forms and using a CheckedListBox control?
Required behaviour:
(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
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:
Upvotes: 4