如何在多个选中的列表框中限制选择?

How to limit selection in more than one checked list boxes?

在 C# 中,checklistbox 我发现以下内容已经足够好了:

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
 {
if (e.NewValue == CheckState.Checked && checkedListBox1.CheckedItems.Count >= 3)
    e.NewValue = CheckState.Unchecked;
 }

但是我有很多复选框,我想对所有复选框实施不同的限制。例如,我想将我的 checkedListBox1 限制为仅 3 个项目选择,而 checkedListBox2 将被限制为 2 个项目选择,依此类推...

我尝试制作多个 checkedListBox_ItemCheck 方法,但 none 似乎影响了其余的检查列表框。它只影响我的第一个。谁能帮帮我?

非常感谢,我才刚刚开始使用 Windows 表格。

编辑:我希望这会让我的目标更加清晰:

假设我有以下 checkedListBoxescheckedListBox1, checkedListbox2, checkedListBox3

这是我正在尝试做的事情:

checkedListBox1 = (/*limit the number of items users are able to select to only 3 items*/);

checkedListBox2 = (/*limit the number of items users are able to select to only 2 items*/);

checkedListBox3 = (/*limit the number of items users are able to select to only 4 items*/);

为了达到这个目的,你可以做以下Method:

       public void LimitCheckedListBoxMaxSelection(int maxCount, ItemCheckEventArgs e)
        {
            if (checkedListBox1.CheckedItems.Count == maxCount)
            {
                if (!checkedListBox1.GetItemChecked(checkedListBox1.SelectedIndex))
                    e.NewValue = e.CurrentValue;
            }
        }


然后要使用它,您必须在 CheckedListBox.
ItemCheck 事件中调用该方法 第一个参数是您要强制执行的限制,即允许的最大检查项目数。
第二个参数是来自控件事件的 ItemCheckEventArgs,默认情况下命名为 e

然而
您还可以制作一个 delegate 并稍微调整 Method 以使其将 ItemCheck 事件附加到您的 CheckedListBox,方法如下:

 public void LimitCheckedListBoxMaxSelection(CheckedListBox checkedLB, int maxCount)
 {
     checkedLB.ItemCheck += (o, args) =>
     {

         if (checkedListBox1.CheckedItems.Count == maxCount)
         {
             if (!checkedListBox1.GetItemChecked(checkedListBox1.SelectedIndex))
                 (args as ItemCheckEventArgs).NewValue = (args as ItemCheckEventArgs).CurrentValue;
         }
     };

 }

然后为了使用它,您必须在表单的 Load 事件中调用此方法,并传递 CheckedListBox 您希望每 [=15 限制一次这样的方法=]:

 private void MainForm_Load(object sender, EventArgs e)
 {

     LimitCheckedListBoxMaxSelection(checkedListBox1, 3);

 }