0

我有一个小程序,在 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);
            }
        }

    }

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

4

1 回答 1

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,则仍保留此事件处理程序以防止检查该项目。

于 2011-12-28T19:45:00.130 回答