Search code examples
c#winformsmdimdichildmdiparent

How could I get the original form instance of an MDI Child in WinForms?


I have a WinForms app which handles different forms as MDI childs and opens them as tabs. Everything related with opening just one instance of each form is actually correctly handled, but I'm facing issues when I throw a "profile changing event".

I want to access a property on the instance of each Child just before closing it, but I'm just accessing to the Form, not the original object form instance itself.

Actual code:

private void ProfileChanged()
{
     foreach (var child in this.MdiChildren)
     {
         child.Close();
     }
}

Desired code:

private void ProfileChanged()
{
     foreach (var child in this.MdiChildren)
     {
         child.Status ...
         child.Close();
     }
}

Any ideas? Many thanks.


Solution

  • You should cast the child variable to your custom Form type. I guess you have a base form that all the child forms inherits from, right? If not, you should have a base class.

    Afterwards, the code should be simple:

    private void ProfileChanged()
    {
        //if you want to use Linq
        foreach (var child in this.MdiChildren.Cast<YourCustomBaseClass>)
        {
            child.Status ...
            child.Close();
        }
        //if you don't want to use Linq
        foreach (var child in this.MdiChildren)
        {
            var myCustomChild = child as YourCustomBaseClass;
            if (myCustomChild == null) continue; //if there are any casting problems
            myCustomChild.Status ...
            myCustomChild.Close();
        }
    
     }