问题描述
在MS Excel中,当您对数据使用过滤器时,有一个“(全选)”选项。
如何在C#中使用Forms并使用 CheckedListBox 控件来做到这一点?
必需的行为:
- “(全选)”在列表中排名第一。
- 选中“(全选)”时,所有其他项目均设置为选中。反之亦然,即未经检查。
(N.B。我正在回答自己的问题,因为我花了太长时间来制定此解决方案,并认为这样做可以节省其他人的时间:)
解决方法
这是按要求执行的代码。
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);
}
}
}
它看起来像这样: