Child form appearing underneath controls on parent form

902 Views Asked by At

I have a C#, .net, Windows Forms application. I have a form set as an MDI container on which I dynamically add buttons. Clicking a button opens a child form. However, the buttons I created appear on top of the child form instead of the child form appearing over (and covering) everything on the parent form. What am I doing wrong?

Here's how I add the buttons to the form:

            Button btn1 = new Button();
            btn1.BackColor = ColorTranslator.FromHtml("#456EA4");
            btn1.Text = department.DepartmentName;
            btn1.Location = new System.Drawing.Point(posX, posY);
            btn1.Size = new System.Drawing.Size(sizeX, sizeY);
            btn1.Font = new System.Drawing.Font("Calibri", 40F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            btn1.ForeColor = Color.WhiteSmoke;
            btn1.TabStop = false;
            this.Controls.Add(btn1);

Here's is where I open the child form:

        frmToBuildFromSchedule frmToBuild = new frmToBuildFromSchedule(department);
        frmToBuild.FormClosed += new FormClosedEventHandler(frmToBuildFromSchedule_FormClosed);
        frmToBuild.MdiParent = this;
        frmToBuild.Show();

Here is the result: enter image description here

2

There are 2 best solutions below

0
JesseChunn On

You are putting the buttons directly on the parent MDI form, which is not typical of an MDI style application. Instead, put the code that is currently in the click event of your buttons in a menu option or a ribbon button (those can also be dynamically created). Alternatively, create a child form, maximize it, and place your buttons on that.

0
Loathing On

I think the answer by sam on the posted duplicate link is interesting. Rather than using MDI, set form.TopLevel = false; and add the form as a child control. I'm not sure if there are any downsides to this approach.

    Form fff = new Form();
    fff.Controls.Add(new Button { Text = "Button1" });

    fff.Load += delegate {
        Form ffff = new Form { TopLevel = false };
        fff.Controls.Add(ffff);
        ffff.Visible = true;
        ffff.BringToFront();
    };


    Application.Run(fff);