Best way to suspend control events in Windows Forms?

Steve Bargelt picture Steve Bargelt · Nov 13, 2008 · Viewed 7.2k times · Source

This seems like a very simple and a very common problem. The simplest example I can think of is this:

The form has five checkboxes with a "check all/check none" checkbox above them. When a user selects checking all checkboxes, I toggle the states of the "children" - obviously I don't want to fire the check events of all the children until I am done setting all of the checkboxes.

I can't find a form-wide suspend control event. If I'm simply missing it then great simple answer. Barring a simple solution that I am just missing, what is the best way (best practice? accepted solution?) to suspend form control events?

Answer

Rob Stevenson-Leggett picture Rob Stevenson-Leggett · Nov 13, 2008

I've come across this before and usually seen people do this:

/*SNIP*/

private bool isMassUpdate;

public void Check1_Check(object sender, EventArgs e)
{
   if(!isMassUpdate)
   {
       do some stuff
   }
}

/*SNIP*/

You can also detach and reattach the event handlers, however, I'm told this can be a source of memory leaks.

Information on memory leaks and event handlers: They're not directly linked to attaching and detaching, but we've seen in one of our applications that bad referencing of event handlers down inheritance trees can cause it.