在不限制大小的c#中动态地向表单添加组件

本文关键字:动态 表单 组件 添加 | 更新日期: 2023-09-27 17:49:58

在程序运行时动态地在表单中添加标签和文本框。如何在滚动窗格中插入这些组件,以便无论添加多少标签和文本框,它们都能适应表单?

我不知道我说的是否清楚。但我想要的是能够添加尽可能多的组件,因为我喜欢,而不是在有限的大小的形式。有什么办法可以做到吗?

这是我现在的代码:

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);
     }
}

谢谢你的帮助

在不限制大小的c#中动态地向表单添加组件

就像别人说的,你不能把它添加到固定表单,然后再调整表单。最终,形式会变得太大。但是,你可以这样做:

1)在表单上添加面板,面板尺寸固定(或锚定/停靠)。2)设置面板自动滚动为true。3)然后添加标签/文本框

所以,如果添加了太多的标签/文本框,滚动条就会显示出来。

但是,为动态控件的#设置一个限制是一个好主意