I agree with the comments that radio buttons would be the usual UI element when only a single item is 'checked', but if you want to stick with a CheckedListBox
for your UI, you can try something like this:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
CheckedListBox.CheckedIndexCollection checkedIndices = checkedListBox1.CheckedIndices;
if (checkedIndices.Count > 0 && checkedIndices[0] != e.Index)
{
checkedListBox1.SetItemChecked(checkedIndices[0], false);
}
}
You also might want to set CheckOnClick
to true
for the CheckedListBox
.
Edit
Updated the code per your comment to deselect an item if it is unchecked. The problem is that unchecking the previously checked item causes the event to fire again. I don't know whether there is a standard way to handle this, but in the code below, I detach the handler before calling SetItemCheck
, then reattach the handler. It seems like a clean way to handle this, and it works. If I find that there is a recommended way to handle this, I will update my answer.
HTH
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
CheckedListBox.CheckedIndexCollection checkedIndices = checkedListBox1.CheckedIndices;
if (checkedIndices.Count > 0)
{
if (checkedIndices[0] != e.Index)
{
// the checked item is not the one being clicked, so we need to uncheck it.
// this will cause the ItemCheck event to fire again, so we detach the handler,
// uncheck it, and reattach the handler
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
checkedListBox1.SetItemChecked(checkedIndices[0], false);
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
else
{
// the user is unchecking the currently checked item, so deselect it
checkedListBox1.SetSelected(e.Index, false);
}
}
}