Reputation: 42440
I am writing a windows forms application that has a check box regarding the application being added to start up (via registry). If the user checks the box, the CheckedChanged event handler triggers a method that attempts to add the application to the registry. If, for any reason, this fails, I want to revert the check box to its unchecked state, however doing so triggers the method again recursively. How can I avoid this?
Similarly, when the application first loads, I look at the registry and accordingly set the initial state of the checkbox. When I programmatically set the state of the checkbox, the even handler fires, which I do not want.
Is there any way I can suppress the even handler from triggering the CheckedChanged method?
Upvotes: 2
Views: 122
Reputation: 144112
A simple way would be to disconnect the handler and reconnect it:
void CheckCbxProgrammatically(bool check)
{
myCbx.CheckedChanged -= HandleCheckedChanged;
myCbx.Checked = check;
myCbx.CheckedChanged += HandleCheckedChanged;
}
You don't want to juggle state when you can avoid it.
Upvotes: 4
Reputation: 11567
A simple flag would suffice.
bool flag;
void ClickEventHandler(Object server, EventArgs e)
{
if (flag) return;
....
}
And set the flag accordingly.
Upvotes: 2
Reputation: 5638
For this kind of cases, I declare a global bool isCalledManually
and set it to true when I don't want it to trigger the event. In the event:
If(isCalledManually)
isCalledManually = false;
Else
// do your operations.
Upvotes: 2