【问题标题】:C# Check All from a CheckedListBox without showing the "Check All" entryC# 从 CheckedListBox 中检查所有而不显示“检查所有”条目
【发布时间】:2011-12-28 19:30:20
【问题描述】:

我有一个小程序,在 VS2010 中有几个复选框列表。我想让用户选择其中一个列表中的所有内容,并提出了这种循环结构......

private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (e.NewValue == CheckState.Checked)
        {
            Applications.Add(CheckedListBox1.Items[e.Index].ToString());
        }
        else if (e.NewValue == CheckState.Unchecked)
        {
            Applications.Remove(CheckedListBox1.Items[e.Index].ToString());
        } 
    }

private void CheckedListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (CheckedListBox1.SelectedIndex == 0)
        {
            for (int i = 1; i < CheckedListBox1.Items.Count; i++)
            {
                CheckedListBox1.SetItemChecked(i, CheckedListBox1.GetItemChecked(0));
            }
        }
        else
        {
            if (!CheckedListBox1.GetItemChecked(CheckedListBox1.SelectedIndex))
            {
                CheckedListBox1.SetItemChecked(0, false);
            }
        }

    }

问题是这也会将“全选”复选框放入输出中。有没有办法可以调整循环以不包括第一个复选框(即“全选”检查)或者我应该以不同的方式解决这个问题?

【问题讨论】:

    标签: c# loops checkbox checkedlistbox


    【解决方案1】:

    很不清楚“进入输出”可能意味着什么。使用 SelectedIndexChanged 事件不是很合适,ItemCheck 事件发出检查项目的信号。试试这个:

        private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
            if (e.Index == 0) {
                for (int item = 1; item < checkedListBox1.Items.Count; item++) {
                    checkedListBox1.SetItemChecked(item, true);
                }
                e.NewValue = CheckState.Unchecked;  // Prevent "Check All" from getting checked
            }
        }
    

    如果您仍然想使用 SelectedIndexChanged,那么仍然保留此事件处理程序以防止项目被检查。

    【讨论】:

    • 抱歉,我应该包含我的 itemcheck 事件。我已经编辑了示例代码来显示这一点。输出存储在列表集合中,然后使用不同的类通过电子邮件发送出去。
    • 这太完美了!我拿出我的 SelectIndexChanged 并将这段代码添加到我的 ItemCheckEvent 中,它绝对完美。谢谢一堆。我很新,已经坚持了一段时间。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多