微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#如何将“全选”选项添加到CheckedListBox,其工作方式类似于MS Excel中的“全选”选项

如何解决C#如何将“全选”选项添加到CheckedListBox,其工作方式类似于MS Excel中的“全选”选项

在MS Excel中,当您对数据使用过滤器时,有一个“(全选)”选项。

enter image description here

如何在C#中使用Forms并使用 CheckedListBox 控件来做到这一点?

必需的行为:

  1. “(全选)”在列表中排名第一。
  2. 选中“(全选)”时,所有其他项目均设置为选中。反之亦然,即未经检查。

(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);
        }
    }
}

它看起来像这样:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。