c# - Winforms checkedlistbox勾选一项

标签 c# winforms .net-3.5

我的表单上有一个 CheckedListBox 控件,我希望用户一次只能检查此列表中的一个项目(所以实际上我想要一些可以模仿“RadioListBox”)。

这可以用 CheckedListBox 来做,还是我必须即兴发挥一些其他方式?

CheckedListBox 通过从数据库加载项目来填充表单加载,以防万一。

谢谢

编辑

我想我应该澄清一下,我并不是要限制用户可以选择的数量(即 SelectionMode 属性),而是他们可以检查的数量。

最佳答案

您可以通过在 CheckedListBox 上为 ItemCheck 添加事件检查并使用如下函数来实现:

    private static bool checkIfAllowed(CheckedListBox listBox) {
        if (listBox.CheckedItems.Count > 0) {
            return false;
        }
        return true;
    }

那么如果你想:

  if (checkIfAllowed) { 
     ...
  } else {

  }

此外,您可以通过添加另一个函数/方法来改进这一点,该函数/方法将在允许检查项目之前取消选中所有项目。因此,当用户单击某个复选框时,所有其他复选框都未选中。

要取消选中所有选中的项目,只需使用:

    private static void uncheckAll(CheckedListBox listBox) {
        IEnumerator myEnumerator;
        myEnumerator = listBox.CheckedIndices.GetEnumerator();
        int y;
        while (myEnumerator.MoveNext() != false) {
            y = (int)myEnumerator.Current;
            listBox.SetItemChecked(y, false);
        }
    }

因此,在 ItemCheck 事件中,您必须先运行 uncheckAll(yourListBox),然后简单地检查项目。

编辑: 我已经使用以下代码对其进行了测试,并且可以正常工作。没有 if 它会抛出异常。

    private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
        if (e.NewValue == CheckState.Checked) {
            IEnumerator myEnumerator;
            myEnumerator = checkedListBox1.CheckedIndices.GetEnumerator();
            int y;
            while (myEnumerator.MoveNext() != false) {
                y = (int)myEnumerator.Current;
                checkedListBox1.SetItemChecked(y, false);
            }
        }

    }

关于c# - Winforms checkedlistbox勾选一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4387013/

相关文章:

c# - 如何使用mysql和c#.net备份数据库

c# - 当我有多个表单时,如何在单击标题栏中的十字时关闭应用程序?

c# - 一个对象上的垃圾收集,C#

c# - 如何从字符串创建属性(集合)表达式选择器?

.net - 如何在自定义控件上添加对 Point 属性的设计器支持?

asp.net - 获取DataPager当前页码

exception - Nlog错误(消息,异常)忽略异常

c# - 在 C# 中打印数组的所有内容

c# - 满足开放/封闭原则的工厂模式?

c# - 从 FileStream 获取字节数组的正确方法是什么?