my checkedlistbox has one condition: Exactly one item has to be checked. That means changing the check the previous item has to be unchecked. That works. But unchecking should not be able. By looking at the GUI after try of uncheck the item is still checked due to the second condition in the ItemCheck-Method. Its not possible to uncheck the current check, how it should be. But after leaving the ItemCheck-Method the count of checked items is changing from 1 to 0 (Property CheckedItems), even though I can see the checked item. Something is missing in my code:
private void myCLB_ItemCheck(object sender, ItemCheckEventArgs e)
{
// 1. Checking one will uncheck all other, works perfectly
if (e.NewValue == CheckState.Checked && myCLB.CheckedItems.Count > 0)
{
myCLB.ItemCheck -= myCLB_ItemCheck;
myCLB.SetItemChecked(myCLB.CheckedIndices[0], false);
myCLB.ItemCheck += myCLB_ItemCheck;
}
// 2. Unchecking without checking another not allowed
if (myCLB.CheckedItems.Count > 0 &&
myCLB.CheckedItems[0].Equals((sender as CheckedListBox).SelectedItem))
{
e.NewValue = CheckState.Checked;
return;
}
// ... do some business here, depending on the check
}
Btw: Using radiobuttons is no option as there is the possible need to use more than one checks. In this case the above constraints will be disabled. I've tried also other variations of the second conditions, which worked also, except that always CheckedItems.Count is changing from 1 to 0 after the ItemCheck-Method is left. I didn't find a validate-method.
Any help will be much appreciated.
As Plutonix suggests, you should consider checking how many are actually checked when the user submits the form. If the user has boxes A and B checked, but later wants boxes C and D checked instead, it'd be very natural for the user to want to uncheck A and B, then check C and D. Your current design doesn't allow this.
But, if you're really boxed in on this, I'd consider setting an Enabled
property to False
when the form is loaded or a checkbox is modified. So if any of the checkboxes have been modified, you'll check if only one is checked, and if so, lock that one down.