user3449768
user3449768

Reputation: 59

MDI Child Forms Opening each other with the same parent form

So I have 3 Forms, lets call them Form1, Form2, and Form3. I have sent the IsMDIParent Property to true for Form1.

When I launch the app, It loads Form2 as an MDI Child using

Form2 frm = new Form2();
frm.MdiParent = this;
frm.Show();

And that works fine. What I then want to do is click a button withing the 2nd form that will close Form2 and open up Form3 as a child form of Form1.

I tried

SecondForm SecondFormMDI = new SecondForm();
SecondFormMDI.MdiParent = Form1;
SecondFormMDI.Show();

on the button click event in Form2, but it would not work.

Do I have to always launch a Child form from the parent form? and if so, how would i go about doing that when it is on the button click event on a child form?

Upvotes: 0

Views: 2567

Answers (4)

Charmy Vora
Charmy Vora

Reputation: 51

ChildForm frmChild = new ChildForm();
frmChild.MdiParent = this.MdiParent;
frmChild.Dock = DockStyle.Fill();
frmChild.Show();

Upvotes: 0

Lali
Lali

Reputation: 2866

Just use this.MdiParent, instead of Form1, like

    SecondForm SecondFormMDI = new SecondForm();
    SecondFormMDI.MdiParent = this.MdiParent;
    SecondFormMDI.Show();

Upvotes: 1

K.L
K.L

Reputation: 7

You could create a method in your MDIForm to open a childform:

public void OpenForm(Form form)
{
    form.MdiParent = this;
    form.Show();
}

When you want to open a new form in another form you do something like this (example in ChildFormOne with button):

private void btnOpenChildFormTwo_Click(object sender, EventArgs e)
{
    ((MDIForm)this.MdiParent).OpenForm(new ChildFormTwo());
    this.Close();
}

Hope this helps.

Upvotes: 0

Zohar Peled
Zohar Peled

Reputation: 82474

You can set the MDIParent of any form in design time, why do it in run-time? Simply set the value of MDIParent property of Form2 and Form3 to Form1, and that's it.

Upvotes: 0

Related Questions