Search code examples
c#winformsmdimdichildmdiparent

C# Winforms, assigning parent to new child object, other than instantiating form


I have an MDI container with two child forms. We've been taught (and the MSDN documentation only gives the example) to use the keyword 'this', which assumes that the child object in question is being created from the MDI container itself.

If I were creating the object in the MDI container, this would be correct:

Form_Child2 child = new Form_Child2(textBox1.Text);
child.MdiParent = this;
child.Show();

Instead, I'm trying to do something more like:

Form_Child2 child = new Form_Child2(textBox1.Text);
child.MdiParent = Form_Parent;
child.Show();

However, this throws an error saying that "Form_Parent" is a type and cannot be used as a variable. I think I vaguely understand what it's getting at, but it's not clear. I've tried studying up on keyword 'this' a bit as well, but still stuck.


Solution

  • Understanding the difference between types and objects is super-duper important if you want to be a C# programmer. Yes, big problem here, an instance of Form_Parent is required here, you cannot use the type name.

    There is only ever one instance of the MDI parent window. Which is something you can take advantage of, you can add a static property to the parent class. Make that look like this:

    public partial class Form_Parent : Form {
    
        public static Form_Parent Instance { get; private set; }
    
        public Form_Parent() {
            InitializeComponent();
            Instance = this;
        }
        // etc..
    }
    

    Now it is very simple:

    Form_Child2 child = new Form_Child2(textBox1.Text);
    child.MdiParent = Form_Parent.Instance;
    child.Show()