您可以通过在 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);
}
}
}