如何动态添加按钮到我的表单?

当我点击button1时,我想在表单上创建10个按钮。 下面的代码没有错误,但它也不起作用。

private void button1_Click(object sender, EventArgs e) { List

它不起作用,因为列表是空的。 试试这个:

 private void button1_Click(object sender, EventArgs e) { List 

您没有创建任何按钮,只有一个空列表。

您可以忘记列表,只需在循环中创建按钮。

 private void button1_Click(object sender, EventArgs e) { int top = 50; int left = 100; for (int i = 0; i < 10; i++) { Button button = new Button(); button.Left = left; button.Top = top; this.Controls.Add(button); top += button.Height + 2; } } 

你可以这样做:

 Point newLoc = new Point(5,5); // Set whatever you want for initial location for(int i=0; i < 10; ++i) { Button b = new Button(); b.Size = new Size(10, 50); b.Location = newLoc; newLoc.Offset(0, b.Height + 5); Controls.Add(b); } 

如果您希望它们以任何合理的方式进行布局,最好将它们添加到其中一个布局面板(即FlowLayoutPanel )或自己对齐它们。

两个问题 – 列表为空。 您需要先将一些按钮添加到列表中。 第二个问题:您无法向“this”添加按钮。 我想,“这个”并没有引用你的想法。 例如,将其更改为引用Panel。

 //Assume you have on your .aspx page:  private void button1_Click(object sender, EventArgs e) { List 

我带来了同样的疑问,目前对我能提出的问题做出了贡献:

  int altura = this.Size.Height; int largura = this.Size.Width; int alturaOffset = 10; int larguraOffset = 10; int larguraBotao = 100; //button widht int alturaBotao = 40; //button height for (int i = 0; i < 50; ++i) { if ((larguraOffset+larguraBotao) >= largura) { larguraOffset = 10; alturaOffset = alturaOffset + alturaBotao; var button = new Button(); button.Size = new Size(larguraBotao, alturaBotao); button.Name = "" + i + ""; button.Text = "" + i + ""; //button.Click += button_Click;//function button.Location = new Point(larguraOffset, alturaOffset); Controls.Add(button); larguraOffset = larguraOffset + (larguraBotao); } else { var button = new Button(); button.Size = new Size(larguraBotao, alturaBotao); button.Name = "" + i + ""; button.Text = "" + i + ""; //button.Click += button_Click;//function button.Location = new Point(larguraOffset, alturaOffset); Controls.Add(button); larguraOffset = larguraOffset+(larguraBotao); } } 

预期的行为是,这将使用窗口大小的当前状态生成按钮,当下一个按钮超出窗口的右边距时,始终断开一条线。

首先,您实际上并没有创建10个按钮。 其次,您需要设置每个按钮的位置,否则它们将显示在彼此的顶部。 这样就可以了:

  for (int i = 0; i < 10; ++i) { var button = new Button(); button.Location = new Point(button.Width * i + 4, 0); Controls.Add(button); } 

如果不创建该Button的新实例,则无法将Button添加到空列表中。 你错过了

 Button newButton = new Button(); 

在你的代码加上摆脱.Capacity

使用像这样的按钮数组。将创建3个动态按钮bcoz h变量的值为3

 private void button1_Click(object sender, EventArgs e) { int h =3; Button[] buttonArray = new Button[8]; for (int i = 0; i <= h-1; i++) { buttonArray[i] = new Button(); buttonArray[i].Size = new Size(20, 43); buttonArray[i].Name= ""+i+""; buttonArray[i].Click += button_Click;//function buttonArray[i].Location = new Point(40, 20 + (i * 20)); panel1.Controls.Add(buttonArray[i]); } }