Notify child controls recursively through C #

I have a form of MainForm , which is a form of Windows Forms, including a plurality of child controls. I want to call a function on MainForm , which will notify all of their children. Does Windows Forms provide this facility? I played with an update, upgrade and void without success.

+4
source share
4 answers
 foreach (Control ctrl in this.Controls) { // call whatever you want on ctrl } 

If you need access to all controls in the form and all the controls for each in the form of control (and so on, recursively), use the following function:

 public void DoSomething(Control.ControlCollection controls) { foreach (Control ctrl in controls) { // do something to ctrl MessageBox.Show(ctrl.Name); // recurse through all child controls DoSomething(ctrl.Controls); } } 

... that you are calling, first passing a Controls collection, for example:

 DoSomething(this.Controls); 
+6
source

Response from MusiGenesis is an elegant (typical in a good way) pleasant and clean.

But simply to offer an alternative to using lambda expressions and "Action" for other types of recursion:

 Action<Control> traverse = null; //in a function: traverse = (ctrl) => { ctrl.Enabled = false; //or whatever action you're performing traverse = (ctrl2) => ctrl.Controls.GetEnumerator(); }; //kick off the recursion: traverse(rootControl); (); Action<Control> traverse = null; //in a function: traverse = (ctrl) => { ctrl.Enabled = false; //or whatever action you're performing traverse = (ctrl2) => ctrl.Controls.GetEnumerator(); }; //kick off the recursion: traverse(rootControl); 
+2
source

No no. You must deploy your own.

On the side of the note - WPF has “routed events” that are just that and more.

+1
source

You need for this recursive method (as shown below), because the control elements may have child elements.

 void NotifyChildren( control parent ) { if ( parent == null ) return; parent.notify(); foreach( control child in parent.children ) { NotifyChildren( child ); } } 
-2
source

All Articles