here what you want:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test_Checklist
{
public class MyCheckListBox : System.Windows.Forms.CheckedListBox
{
List<object> all = new List<object>();
List<int> chks = new List<int>();
bool showChecked = false;
public MyCheckListBox()
: base()
{
this.ItemCheck += MyCheckListBox_ItemCheck;
}
void MyCheckListBox_ItemCheck(object sender, System.Windows.Forms.ItemCheckEventArgs e)
{
if (!this.showChecked)
return;
var o = this.Items[e.Index];
int oi = all.IndexOf(o);
if (e.NewValue == System.Windows.Forms.CheckState.Checked)
chks.Add(oi);
else
chks.Remove(oi);
}
public void ShowOnlyChecked(bool val)
{
this.showChecked = val;
if (val)
{
all.AddRange(this.Items.Cast<object>());
chks.AddRange(this.CheckedIndices.Cast<int>());
for (int i = 0; i < all.Count; i++)
if (!chks.Contains(i))
this.Items.Remove(all[i]);
}
else
{
this.Items.Clear();
this.Items.AddRange(this.all.ToArray());
this.chks.ForEach(i1 => this.SetItemChecked(i1, true));
all.Clear();
chks.Clear();
}
}
}
}
and an example form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test_Checklist
{
public partial class Form1 : Form
{
MyCheckListBox lb = new MyCheckListBox();
public Form1()
{
InitializeComponent();
this.SuspendLayout();
this.Controls.Add(lb);
this.lb.Items.AddRange(new string[] { "item1", "item2", "item3" });
this.lb.Left = this.checkBox1.Left;
this.lb.Top = this.checkBox1.Top + 20;
this.ResumeLayout(false);
this.checkBox1.CheckState = CheckState.Unchecked;
this.checkBox1.CheckedChanged += checkBox1_CheckedChanged;
}
void checkBox1_CheckedChanged(object sender, EventArgs e)
{
switch (this.checkBox1.CheckState)
{
case CheckState.Checked:
this.lb.ShowOnlyChecked(true);
break;
case CheckState.Indeterminate:
case CheckState.Unchecked:
this.lb.ShowOnlyChecked(false);
break;
default:
break;
}
}
}
}
It doesn't have designer support, but you can convert it into custom control.