Tarion
Tarion

Reputation:

Recursively notify child controls via C#

I have a form MainForm which is a Windows Forms form that contains many child controls. I want to call one function on MainForm that notifies all of its children. Does the Windows Forms form provide a means to do this? I played with update, refresh and invalidate with no success.

Upvotes: 4

Views: 4203

Answers (4)

Muad'Dib
Muad'Dib

Reputation: 29216

You are going to need a recursive method to do this (as below), because controls can have children.

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

Upvotes: -2

Nick Josevski
Nick Josevski

Reputation: 4216

The answer from MusiGenesis is elegant, (typical in a good way), nice and clean.

But just to offer an alternative using lambda expressions and an 'Action' for a different type 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);

Upvotes: 2

MusiGenesis
MusiGenesis

Reputation: 75276

foreach (Control ctrl in this.Controls)
{
    // call whatever you want on ctrl
}

If you want access to all controls on the form, and also all the controls on each control on the form (and so on, recursively), use a function like this:

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);
    }
}

... which you call by initially passing in the form's Controls collection, like this:

DoSomething(this.Controls);

Upvotes: 6

Vilx-
Vilx-

Reputation: 106920

No, there isn't. You must roll out your own.

On a side note - WPF has "routed events" which is exactly this and more.

Upvotes: 1

Related Questions