C# CheckedListBox 只允许选中一项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10553323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:17:16 来源:igfitidea点击:
CheckedListBox allowing only one item to be checked
提问by Ahmed
In my CheckedListBoxapp I want to allow only a single item to be checked.
在我的CheckedListBox应用程序中,我只想允许检查一个项目。
I have these properties already set
我已经设置了这些属性
checkOnClick = true;
SelectionMode = One;
Any advise will be appreciated
任何建议将不胜感激
采纳答案by Zaki
uncheck all other items in ItemCheck event as below :
取消选中 ItemCheck 事件中的所有其他项目,如下所示:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix)
if (ix != e.Index) checkedListBox1.SetItemChecked(ix, false);
}
回答by Nicolas Tyler
the best way to do this is like this:
最好的方法是这样的:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Checked && checkedListBox1.CheckedItems.Count > 0)
{
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
checkedListBox1.SetItemChecked(checkedListBox1.CheckedIndices[0], false);
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
}
no looping is always better.
没有循环总是更好。

