CheckedListBox allowing only one item to be checked

点点圈 提交于 2019-11-27 15:04:17

问题


In my CheckedListBox app I want to allow only a single item to be checked.

I have these properties already set

checkOnClick = true;
SelectionMode = One;

Any advise will be appreciated


回答1:


uncheck all other items in ItemCheck event as below :

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);
    }



回答2:


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.



来源:https://stackoverflow.com/questions/10553323/checkedlistbox-allowing-only-one-item-to-be-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!