Reputation: 612
I have a form that contains two elements: a CheckedListBox
and a CheckBox
. The CheckBox
, which is called SelectAllCheckBox
, is used to check/uncheck all items in the CheckedListBox
. I achieve this via a CheckedChanged
event handler associated with the SelectAllCheckBox
, so that when it is checked, all items in the CheckedListBox
are checked, and vice versa. This works fine.
I also have code that unchecks the SelectAllCheckBox
when the user unchecks one of the CheckBoxes in the CheckedListBox
. For example, if the user checks the SelectAllCheckBox
, and then unchecks one of the items, the Select All CheckBox
should be unchecked. This is achieved via the CheckedListBox.ItemChecked
event handler. This also works fine.
My problem is that when the SelectAllCheckBox
is programatically unchecked (as in the above scenario), its event handler causes all items in the CheckedListBox
to become unchecked.
I'm sure others have run into my issue; is there an elegant workaround?
Upvotes: 2
Views: 6384
Reputation: 6769
Another way is to utilize the fact that when you programmatically check/uncheck, it does not give focus to the checkbox. So you can use the Focused
property as a flag.
private void SelectAllCheckBox_CheckedChanged(object sender, EventArgs e)
{
if(!((CheckBox)sender).Focused)
return;
//your code to uncheck/check all CheckedListBox here
}
No need to create another separate bool flag (unless if you are manually changing the focus state somewhere).
Upvotes: 2
Reputation: 63317
You can use some flag:
bool suppressCheckedChanged;
private void SelectAllCheckBox_CheckedChanged(object sender, EventArgs e){
if(suppressCheckedChanged) return;
//your code here
//....
}
//Then whenever you want to programmatically change the Checked of your SelectAllCheckBox
//you can do something like this
suppressCheckedChanged = true;
SelectAllCheckBox.Checked = false;
suppressCheckedChanged = false;
Another approach is you can try another kind of event such as Click
and DoubleClick
(must use both):
private void SelectAllCheckBox_Click(object sender, EventArgs e){
DoStuff();
}
private void SelectAllCheckBox_DoubleClick(object sender, EventArgs e){
DoStuff();
}
private void DoStuff(){
//your code here;
if(SelectAllCheckBox.Checked){
//....
}
else {
//....
}
}
Upvotes: 2