Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to suspend control events in Windows Forms?

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?

like image 398
Steve Bargelt Avatar asked Nov 13 '08 17:11

Steve Bargelt


People also ask

What is SuspendLayout in Winforms?

The SuspendLayout and ResumeLayout methods are used in tandem to suppress multiple Layout events while you adjust multiple attributes of the control.

How do you put controls on a form?

Add the control by drawingSelect the control by clicking on it. In your form, drag-select a region. The control will be placed to fit the size of the region you selected.

What Windows form controls?

Windows Forms controls are reusable components that encapsulate user interface functionality and are used in client-side, Windows-based applications. Not only does Windows Forms provide many ready-to-use controls, it also provides the infrastructure for developing your own controls.


2 Answers

What I do in these cases instead of having a boolean value that suspends events, I use a counter. When the count is > 0, then suspend events, when the count = 0, then resume events. This helps with the problem if I have multiple things that could request a suspension of events.

The other useful thing is if I need to suspend events in a block, I create a little helper class that is IDisposable that I can use in a "using" block (in C#) so I don't forget to decrement the counter once I'm out of scope.

like image 177
Garo Yeriazarian Avatar answered Oct 23 '22 18:10

Garo Yeriazarian


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.

  • .NET Memory Leak Case Study: The Event Handlers That Made The Memory Baloon

  • On event handlers and memory leaks

like image 6
Rob Stevenson-Leggett Avatar answered Oct 23 '22 19:10

Rob Stevenson-Leggett