I am dynamically adding labels and textboxes in a form while the program is running. How can I insert these components in a scroll pane so that no matter how many labels and textboxes I add they will fit in the form?
I don’t know if I’m being clear.. but what I want is to be able to add as many components as I like and not in the limited size of the form.. is there any way to do this?
This is my code right now:
public void generateFormDynamically()
{
textBoxes = new TextBox[noOfPlayers];
int xLabel = 95;
int yLabel = 215;
int xTextBox = 205;
int yTextBox = 215;
for (int i = 0; i < noOfPlayers; i++)
{
Label label = new Label();
label.Text = "Player " + (i + 1) + ":";
if (i == 0) label.Location = new Point(xLabel, yLabel);
else
{
yLabel += 55;
label.Location = new Point(xLabel, yLabel);
}
label.AutoSize = true;
label.BackColor = System.Drawing.Color.Transparent;
label.Font = new System.Drawing.Font("Segoe UI Semibold", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
label.Name = "label" + (i + 2);
label.Size = new System.Drawing.Size(68, 20);
label.TabIndex = 6;
label.Visible = true;
label.Show();
this.Controls.Add(label);
TextBox textBox = new TextBox();
if (i == 0) textBox.Location = new Point(xTextBox, yTextBox);
else
{
yTextBox += 55;
textBox.Location = new Point(xTextBox, yTextBox);
}
textBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
textBox.Name = "textBox" + (i + 1);
textBox.Size = new System.Drawing.Size(245, 20);
textBox.TabIndex = 1;
textBox.Text = "Player" + (i + 1);
textBox.Visible = true;
textBox.Show();
textBoxes[i] = textBox;
this.Controls.Add(textBox);
}
}
Thanks for your help 🙂
As others said, you can not add it to fixed form, and then adjust form. eventually, form will be too big. BUT, you can do is:
1) add a panel on the form, the panel size is fixed (or anchored/docked).
2) set panel AutoScroll to true.
3) then add label/textbox.
so, if too many label/textbox added, the scrollbar will show up.
but still, it is a good idea to set a limit for the # of dynamic control.