views:

804

answers:

4

I have my MainForm, it's a Windows Forms form. There are many child controls and now I want to call one function on my MainForm that notifies all children. Is there something to use in the Windows Forms form? I played with update, refresh and invalidate with no success.

+1  A: 

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

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

Vilx-
+2  A: 
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);
MusiGenesis
I would implement DoSomething in an interface like "ICanDoSomething" and prrof that interface in the foreach. So you have to add only this interface for each control.
Tarion
A: 

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 );
    }
}
Muad'Dib
What language is this?
MusiGenesis
as the title of the question says, this is C#
Muad'Dib
Controls in WinForms don't have a "children" collection.
MusiGenesis
A: 

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);
Nick Josevski