private void button1_Click(object sender, EventArgs e) { List
它不起作用,因为列表是空的。 试试这个:
private void button1_Click(object sender, EventArgs e) { List buttons = new List(); for (int i = 0; i < 10; i++) { Button newButton = new Button(); buttons.Add(newButton); this.Controls.Add(newButton); } }
您没有创建任何按钮,只有一个空列表。
您可以忘记列表,只需在循环中创建按钮。
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); }
//Assume you have on your .aspx page: private void button1_Click(object sender, EventArgs e) { List buttons = new List(); for (int i = 0; i < buttons.Capacity; i++) { Panel_Controls.Controls.Add(buttons[i]); } }
我带来了同样的疑问,目前对我能提出的问题做出了贡献:
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); } }