0

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

boilers222
  • 1,901
  • 7
  • 33
  • 71
  • Your this in this.Controls.Add is most likely the MDI parent, you want to add it to the child so it should be code like this.Controls(ChildName).Controls.Add(btn1) – Aldert May 24 '21 at 20:35
  • Does this answer your question? [Controls in container form come over child form?](https://stackoverflow.com/questions/4808109/controls-in-container-form-come-over-child-form) – Loathing May 24 '21 at 20:52
  • Controls directly in the MdiClient area don't work well. Instead, place a PANEL in the MdiParent and DOCK it to one side. Add any controls you want in that Panel. This will correctly reduce the size of the MdiClient area and make any MdiChildren correctly display. – Idle_Mind May 25 '21 at 04:53

2 Answers2

0

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.

JesseChunn
  • 555
  • 3
  • 7
0

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);
Loathing
  • 5,109
  • 3
  • 24
  • 35