0

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.

Gonzo345
  • 1,133
  • 3
  • 20
  • 42

2 Answers2

3

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

 }
Mihail Stancescu
  • 4,088
  • 1
  • 16
  • 21
  • Thanks for your reply. I finally needed to do a this.MdiChildren.Select(frm => frm as frmBaseEntity) instead of the .Cast :) – Gonzo345 Jul 17 '17 at 07:02
0

you can cast your child as Formxxx... where Formxxx is the type of each Form example:

public partial class Form1 : Form
{
    public int Status { get; set; }
    public Form1()
    {
        InitializeComponent();

    }

    private void ProfileChanged()
    {
        foreach (var child in this.MdiChildren)
        {
            if (child is Form1)
            {
            (child as Form1).Status = 1;
              child.Close();
            }
        }

    }
}
Xavave
  • 645
  • 11
  • 15