Open MDI form and close one when opening another?

Asked

Viewed 3,190 times

2

My question is, how do I open a form on an MDI and after opening another the previous one closes or simply MDI.

I know this is not the right but it will give to understand what I want!

  Form Consulta = new frmConsulta();
            if (Consulta.Show == true) //Se consulta estiver aberto e apenas oculto
            {
                Consulta.Hide(); //então apareça
            }
            else// se não
            {
                Consulta.Show();// abra
            }

1 answer

3


To do this you can use the property Openforms, which is a collection with open forms, follow an example of how to use:

using System.Windows.Forms;

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

    private void FecharFormulariosFilhos()
    {
        // percorre todos os formulários abertos
        for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
        {
            // se o formulário for filho
            if (Application.OpenForms[i].IsMdiChild)
            {
                // fecha o formulário
                Application.OpenForms[i].Close();
            }
        }
    }

    private void btnFilho1_Click(object sender, System.EventArgs e)
    {
        FecharFormulariosFilhos();

        // cria a exibe o formulário filho
        frmFilho1 frmFilho = new frmFilho1();
        frmFilho.MdiParent = this;
        frmFilho.Show();
    }

    private void btnFilho2_Click(object sender, System.EventArgs e)
    {
        FecharFormulariosFilhos();

        // cria a exibe o formulário filho
        frmFilho2 frmFilho = new frmFilho2();
        frmFilho.MdiParent = this;
        frmFilho.Show();
    }
}

I used the property IsMdiChild as a parameter to check which forms should be closed, but you can use others, for example Name or Text.

Note: the frmPrincipal (parent form) is also in the collection.

The reason I used a for regressive and not a foreach or a for normal, it is because it would make an error, as discussed in this question Close all open Forms except the main menu in c#.

  • Brawling man helped a lot...!!

  • @Matthew, good answer

  • 1

    You helped me a lot. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.