2013-10-18 185 views
1
private void button1_Click(object sender, EventArgs e) 
{ 
    string a = textBox1.Text; 
    int h = Convert.ToInt32(a); 

    for (int i = 0; i <= h; i++) 
    { 
     buttonArray[i] = new Button(); 
     buttonArray[i].Size = new Size(60, 23); 
     buttonArray[i].Location = new Point(40,20); 
     panel1.Controls.Add(buttonArray[i]); 
    } 
} 

我的任務是如果用戶在文本框中輸入3。 3個按鈕應該動態創建並添加到面板如何做到這一點?我使用的按鈕陣列,請建議我在面板上動態添加按鈕和按鈕對象

+0

你的結果是什麼? – doge

+0

哪種類型的面板? – progpow

+0

你的代碼實際上工作的唯一問題是位置,每個按鈕總是相同的,試試這個buttonArray [i] .Location = new Point(40,20+(i * 20)); – Sam

回答

0

例如,你可以使用它。

private void button1_Click(object sender, EventArgs e) 
    { 
     panel1.Controls.Clear(); 
     string a = textBox1.Text; 
     int h = Convert.ToInt32(a); 

     for (int i = 0; i <= h; i++) 
     { 
      var btn = new Button {Size = new Size(60, 23), Dock=DockStyle.Left, Text=h.ToString() }; 
      btn.Click+= delegate(object sender, EventArgs e) { //your commands }; 
      panel1.Controls.Add(btn); 
     } 
    } 
+0

就我個人而言,我總是在動態部分周圍添加一個suspendLayout()&ResumeLayout(false),同時我認爲上面的代碼應該事先有一個pannel1.Controls.Clear()? –

+0

好吧,現在我需要知道如何添加事件動態按鈕 – rithish

+0

我chnage現在 – progpow

0

this post已經回答了類似的問題:

private void button1_Click(object sender, EventArgs e) 
    { 
     string a = textBox1.Text; 
     int h = Convert.ToInt32(a); 

     for (int i = 0; i <= h; i++) 
     { 
      var b = new Button { Size = new Size(60, 23), Location = new Point(4 + i * 57, 20), Text = string.Format("button{0}", i) }; 
      b.Click += b_Click; 
      panel1.Controls.Add(b); 
     } 
    } 

    void b_Click(object sender, EventArgs e) 
    { 
     throw new NotImplementedException(); 
    } 

它需要測試驗證,始終得到了衆多

string a = textBox1.Text; 
0

可使用列表更situable ?

List<Button>Buttons=new List<Buttons>(); 

private void button1_Click(object sender, EventArgs e) 
{ 
    Buttons.Clear(); 
    string a = textBox1.Text; 
    //here should be checking if "a" is digit and is not empty 
    int h = Convert.ToInt32(a); 

    for (int i = 0; i <= h; i++) 
    { 
     Button btn=new Button(); 
     btn.Parent=panel1; 
     btn.Size=new Size(60, 23); 
     btn.Location = new Point(40,5+25*i); //arrange verically 
     btn.Text = "Button "+i.ToString(); 
     btn.Click+=btn_Click; 
     btn.Tag="Some Value you want to restore after button click"; 

     Buttons.Add(btn) 
    } 
}