How can I place dynamic controls on dynamic forms?

253 Views Asked by At

I am trying to make custom forms with unique sets of controls on each form... I can create the dynamic form, but I can't seem to put any controls on it..

using (Form formA = new Form())
{
  Button btn = new Button();
  formA.Text = "Form A";
  formA.Name = "FormA";
  this.MaximizeBox = false;
  this.MinimizeBox = false;
  this.BackColor = Color.White;
  this.ForeColor = Color.Black;
  this.Size = new System.Drawing.Size(155, 265);
  this.Text = "Run-time Controls";
  this.FormBorderStyle = FormBorderStyle.FixedDialog;
  this.StartPosition = FormStartPosition.CenterScreen;
  formA.Show();
  formA.Controls.Add(btn);
}

The form creates ok, but no luck on the buttons... (I edited the code displayed here, to make it easier to see what I am trying to do, but my form still destroys itself as soon as it is created. I have no idea why.

2

There are 2 best solutions below

0
Franck On

First the formA.ShowDialog(); will freeze there until the form is closed. Second the button you created only one and moved it around.

Change with the following :

using (Form formA = new Form()) 
{
   formA.Text = "Form A";
   formA.Name = "FormA";
   this.MaximizeBox = false;
   this.MinimizeBox = false;
   this.BackColor = Color.White;
   this.ForeColor = Color.Black;
   this.Size = new System.Drawing.Size(155, 265);
   this.Text = "Run-time Controls";
   this.FormBorderStyle = FormBorderStyle.FixedDialog;
   this.StartPosition = FormStartPosition.CenterScreen;
   formA.Show();

   for (int x = 0; x <= 3; x++)
   {
      Button btn = new Button();
      btn.Location = new System.Drawing.Point(10 + (x * 5), 10 + (x * 5));
      btn.Text = "Button" + x.ToString();
      btn.Name = "Button_" + x.ToString(); 
      formA.Controls.Add(btn);
   }
}
0
william_perry On

Solved it with the following:

Button btn = new Button();
Form formA = new Form();
formA.Text = "Form A";
formA.Name = "FormA";
this.MaximizeBox = false;
this.MinimizeBox = false;
this.BackColor = Color.White;
this.ForeColor = Color.Black;
this.Size = new System.Drawing.Size(155, 265);
this.Text = "Run-time Controls";
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.StartPosition = FormStartPosition.CenterScreen;
formA.Show();
formA.Controls.Add(btn);