gpt4 book ai didi

c# - Winforms checkedlistbox勾选一项

转载 作者:太空狗 更新时间:2023-10-30 01:26:40 26 4
gpt4 key购买 nike

我的表单上有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com