Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MDI form in C# Parent And Child

Tags:

c#

winforms

mdi

I have 3 forms on my project.

  • form1 is MDI controller
  • form2 and form3 are MDI children

How do I create form1 as the parent and form2 and form3 as children?

Something like old MFC's MDI interface:

enter image description here

Imagine form2 is the parent and has a button. If clicked, it must open form3 in the parent form (form1). How do I set this up?

like image 329
user763274 Avatar asked Dec 21 '22 13:12

user763274


2 Answers

Firstly, make sure Form1's IsMdiContainer is set to true.

Then instantiate Form1 and Form2, setting Form1 to be Form2's MdiParent:

// Form1.IsMdiContainer should be true
Form1 form1 = new Form1();

// This automatically adds form2 into form1's MdiChildren collection
Form2 form2 = new Form2();
form2.MdiParent = form1;

In Form2's code, have something like the following to handle the button's click event to instantiate Form3.

public class Form2 : Form {
    // Include as data member so we only instantiate one Form3
    Form3 _form3;

    public Form2() {
        InitializeComponent();
        Button1.Click += new EventHandler(Button1_Click);
    }

    private void Button1_Click(object sender, EventArgs e) {
        if(_form3 == null) {
            _form3 = new Form3();
            // Set Form3's parent to be Form1
            _form3.MdiParent = this.MdiParent;
        }
    }
}

As a couple notes, this code is really quick and dirty. There are several undesirable things about it like the coupling of Form2 and Form3 (as well as unhelpful class names Form1, Form2, and Form3). Ideally, you'd decouple Form2 and Form3 by raising an event from Form2 that your forms container can hook onto and instantiate Form3. This sample code is meant to give you a direction.

like image 63
bitxwise Avatar answered Jan 05 '23 11:01

bitxwise


Just tell to the form that its MdiParent is current form.

  form2 frm = new form2 ();
    frm.MdiParent = this;
    frm.Show();
like image 40
Senad Meškin Avatar answered Jan 05 '23 13:01

Senad Meškin