Open form in MDI and close one when opening another?

1

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

I know this is not the right one but you can 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
            }
    
asked by anonymous 25.12.2014 / 19:24

1 answer

1

To do this you can use the #, which is a collection with open forms, is 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 IsMdiChild property as a parameter to check which forms should be closed, but you can use others, for example Name or Text .

  

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

The reason I have to use a for fault, not a foreach or a for normal, is why I'd give it an error, as discussed in this question

25.12.2014 / 22:19