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

问题描述:

在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方法,但似乎没有影响checklistboxes的其余部分。它只影响我的第一个。任何人都可以帮助我吗?

非常感谢,我刚刚开始使用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*/);

+0

所以你有一个checkedListbox,你想限制你的用户只能检查限制数量的checkboxitems? – Niklas

+0

我有几个checkedListBoxes,我想做一个函数来限制不同checkedListBoxes的选择。例如:(checkedListBox1 =限制选择项目的数量为3个项目); (checkedListBox2 =限制只选择2项的项目数); (checkedListBox3 =限制只选择4项的项目数);等.... – 5120bee

+0

让我知道如果这适用于你,我测试它,它在我的情况下工作。 – Niklas

为了实现这一点,你可以进行以下Method

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


然后使用它,你就必须调用该方法在ItemCheck事件CheckedListBox的。
第一个参数是您要强制执行的限制,即允许的最大检查项数。
第二个参数是控件事件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通过以下方法按CheckedListBox

private void MainForm_Load(object sender, EventArgs e) 
{ 

    LimitCheckedListBoxMaxSelection(checkedListBox1, 3); 

} 
+0

嗨!对不起,有点迟到了。我想我的问题是因为我在我的设计器文件中遗漏了“this.CheckedBoxtList .....”这行代码。但是我从你发布的内容中学到了很多东西。下次我使用Windows窗体时,我会尽量记住它。再次感谢! :) – 5120bee

+0

@ 5120bee我很高兴我帮助! :) – Niklas