Reputation: 1277
I'm using the following code to limit the number of checked items in a CheckedListBox to 1:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (checkedListBox1.CheckedItems.Count == 1)
{
Boolean isCheckedItemBeingUnchecked = (e.CurrentValue == CheckState.Checked);
if (isCheckedItemBeingUnchecked)
{
e.NewValue = CheckState.Checked;
}
else
{
Int32 checkedItemIndex = checkedListBox1.CheckedIndices[0];
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
checkedListBox1.SetItemChecked(checkedItemIndex, false);
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
return;
}
}
But there are occasions where I need to clear all checked items. I'm using the code below to try to do that but the previous event is preventing that from working. How can I accomplish that? Thanks.
public void ClearChecked()
{
foreach (int checkedItemIndex in checkedListBox1.CheckedIndices)
{
checkedListBox1.SetItemChecked(checkedItemIndex, false);
}
}
Upvotes: 2
Views: 4311
Reputation: 216273
The simplest way is disconnecting the ItemChecked event handler, perform the uncheck and then reconnect the event handler. In this way, when you call SetItemChecked no ItemChecked event will be fired and you don't need any additional code to control your event handler. Just noticed that you already are using this pattern inside your ItemCheck event.
public void ClearChecked()
{
try
{
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
foreach (int checkedItemIndex in checkedListBox1.CheckedIndices)
{
checkedListBox1.SetItemChecked(checkedItemIndex, false);
}
}
finally
{
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
}
The try/finally is important, because, in case of exceptions your event handler will be reconnected.
Upvotes: 1
Reputation: 53
This should clear all checked items:
public void UncheckCheckBoxItems(CheckBoxList cbl)
{
foreach (ListItem item in cbl.Items)
{
item.Selected = false;
}
}
Upvotes: 2
Reputation: 13057
You could create a new variable indicating when the ItemCheck event should be ignored:
private shouldIgnoreCheckEvent;
public void ClearChecked()
{
this.shouldIgnoreCheckEvent = true;
foreach (int checkedItemIndex in checkedListBox1.CheckedIndices)
{
checkedListBox1.SetItemChecked(checkedItemIndex, false);
}
this.shouldIgnoreCheckEvent = false;
}
and update your ItemCheck method to check if it should be ignored or not:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (!this.shouldIgnoreCheckEvent && checkedListBox1.CheckedItems.Count == 1)
{
Boolean isCheckedItemBeingUnchecked = (e.CurrentValue == CheckState.Checked);
if (isCheckedItemBeingUnchecked)
{
e.NewValue = CheckState.Checked;
}
else
{
Int32 checkedItemIndex = checkedListBox1.CheckedIndices[0];
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
checkedListBox1.SetItemChecked(checkedItemIndex, false);
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
return;
}
}
Upvotes: 2