Ali Vojdanian
Ali Vojdanian

Reputation: 2111

Child form in a mdi parent in C#

I use the following codes for showing child form in a MDI parent form. As you know clicking the button will cause a new form to appear. Keep clicking the button and your screen will be filled with blank forms. To stop this from happening, I moved the code that creates the form outside of the button.

Like this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    Form2 f2 = new Form2();    

    private void button1_Click(object sender, EventArgs e)
    {
        f2.MdiParent = this;
        f2.Show();
    }

But when I close the child form and want to open it again, it won't let me.

Please help me to solve this.

Upvotes: 1

Views: 9080

Answers (2)

riffnl
riffnl

Reputation: 3183

You don't want to keep all your forms (twice) as variables. All mdi forms are added to your MdiChildren collection. So, you'd want to check if you need to show the form you've created. Like so:

private void button1_Click(object sender, EventArgs e) 
{ 
    Form2 f2 = new Form2();
    f2.MdiParent = this; 
    OpenMdiChild(f2);
} 
private void OpenMdiChild(Form newForm)
{
    bool found = false;
    foreach (Form frm in this.MdiChildren)
    {
        if (frm.GetType() == newForm.GetType())
                {
                        frm.Activate();
                        frm.Focus();
                        //frm.BringToFront();
            found = true;
            break;
                }
    }
    if (!found)
    {
        frm.Show();
    }
}

If you want the users just to open 1 form, you could change the OpenMdi-- method to this:

private void OpenMdiChild(Form newForm) 
{ 
    bool found = (this.MdiChildren.Length > 0);  
    if (!found) 
    { 
        foreach (Form frm in this.MdiChildren) 
        { 
            if (frm.GetType() == newForm.GetType()) 
            { 
            frm.Activate(); 
                    frm.Focus(); 
                    //frm.BringToFront(); 
                    found = true; 
                break; 
                } 
        } 
    if (!found)
    {
            frm.Show(); 
    }
    } 
}

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941465

You need to keep track of the form state so you know you need to create a new one. Like this:

private Form2 f2;    

private void button1_Click(object sender, EventArgs e)
{
    if (f2 == null) {
       f2 = new Form2();
       f2.MdiParent = this;
       f2.FormClosed += delegate { f2 = null; };
       f2.Show();
    }
    else {
       f2.Activate();
    }
}

Upvotes: 5

Related Questions