Search code examples
c#winformsmdichildsplitcontainer

Closing mdi child in SplitContainer


i'm developping a winforms application and i'm putting a mdi child form in splitcontainer.panel1. when i want to close current mdi child to open another one i can't get the child form. i'm using this code to open e new child but i want get the current child to close it :

            Accueil accueil = new Accueil();
            accueil.MdiParent = this;
            accueil.TopLevel = false;
            this.splitContainer1.Panel1.Controls.Add(accueil);
            accueil.WindowState = FormWindowState.Maximized;
            accueil.Size = this.splitContainer1.Panel1.ClientSize;
            accueil.MinimizeBox = false;
            accueil.MaximizeBox = false;
            accueil.ControlBox = false;
            accueil.Width = this.splitContainer1.Panel1.Width;
            accueil.Height = this.splitContainer1.Panel1.Height;
            accueil.Show();

Solution

  • Putting an MDI child window into a split container doesn't make any sense. You are turning the form into a plain control by setting its TopLevel property to false. Best not to lose the reference. But you will probably be ahead with:

        while (splitContainer1.Panel1.Controls.Count > 0)
            splitContainer1.Panel1.Controls[0].Dispose();
        var accueil = new Accueil();
        accueil.TopLevel = false;
        accueil.Dock = DockStyle.Fill;
        accueil.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
        accueil.Visible = true;
        this.splitContainer1.Panel1.Controls.Add(accueil);
    

    Do consider using a UserControl instead, it is the sane approach with the least likely long-term confuzzlement.