Search code examples
c#winformsmdimdiparent

Child Form's MDI Parent Property Becomes Null in Windows Forms C#


I'm a 13-year-old learning C# and I've come across an issue in my Windows Forms application. The MDI parent property of a child form becomes null after adding it to a panel. Below is the relevant code snippet:

public void OpenChildForm(Form childForm, object btnSender)
{
    previousForm = null;
    ActivateButton(btnSender);
    if (activeForm != null)
        activeForm.Close();
    childForm.MdiParent = this;
    childForm.TopLevel = false;
    childForm.FormBorderStyle = FormBorderStyle.None;
    childForm.Dock = DockStyle.Fill;
    this.panelDesktopPane.Controls.Add(childForm);
    childForm.BringToFront();
    childForm.Show();
    lblTitle.Text = childForm.Text;
}

After dynamically adding a child form to a panel, I've noticed that its MDI parent property becomes null, resulting in unexpected behavior by adding breakpoints i found out that the mdiparent property becomes null right after the form is added to panelDesktopPane


Solution

  • The issue you’re facing is due to the fact that a Form cannot be both an MDI child and a control on a Panel at the same time. When you add the form to the Panel’s controls, it ceases to be an MDI child and its MdiParent property becomes null.

    Removing the following line from your code should solve the problem:

    childForm.MdiParent = this;