CheckedListBox allowing only one item to be checke

2020-02-09 03:30发布

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

2条回答
倾城 Initia
2楼-- · 2020-02-09 04:21

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.

查看更多
劳资没心,怎么记你
3楼-- · 2020-02-09 04:29

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);
    }
查看更多
登录 后发表回答