2014-02-08 101 views
4

我想創建Button的動態的動態的數量通過給範圍在TextBox如何刪除動態創建的按鈕

問題是,當我輸入範圍例如(3)。它會創建3個按鈕,但是當我給出的範圍小於例如(2)之前給出的範圍時。它不顯示2個按鈕,它向我顯示前3個按鈕。我的代碼適用於大於先前範圍的範圍,但在新範圍小於上一範圍時失敗。

這裏是我的代碼:

private void button2_Click(object sender, EventArgs e) 
{ 
    int number = int.Parse(textBox3.Text); 
    Button[] textBoxes = new Button[number]; 
    int location = 136; 

    for (int i = 0; i < textBoxes.Length; i++) 
    { 
     location += 81; 
     var txt = new Button(); 
     textBoxes[i] = txt; 
     txt.Name = "text" + i.ToString(); 
     txt.Text = "textBox" + i.ToString(); 
     txt.Location = new Point(location, 124); 
     txt.Visible = true; 
     this.Controls.Add(txt); 
    } 
} 
+0

爲什麼你給'Button'數組命名如'textBoxes'? –

+0

首先我想創建文本框。所以我忘了改名字。 – Loyal

回答

3

您不刪除以前的控件。您可以創建新的之前將它們存儲在一個數組,然後刪除它們:

class Form1 : Form { 
    private Button[] _textBoxes; 

    private void button2_Click(object sender, EventArgs e) { 
     int number = int.Parse(textBox3.Text); 
     if(_textBoxes != null) { 
      foreach(Button b in _textBoxes) 
       this.Controls.Remove(b); 
     } 

     _textBoxes = new Button[number]; 
     int location = 136; 

     for (int i = 0; i < textBoxes.Length; i++) { 
      location += 81; 
      var txt = new Button(); 
      _textBoxes[i] = txt; 
      txt.Name = "text" + i.ToString(); 
      txt.Text = "textBox" + i.ToString(); 
      txt.Location = new Point(location, 124); 
      txt.Visible = true; 
      this.Controls.Add(txt); 
     } 
    } 
} 

我沒有測試代碼,但我希望你的想法。

+0

非常感謝它的作品! – Loyal

+0

@歡迎您光臨:) – BlackBear

2

它沒有出現故障,正在發生的事情是您創建重疊以前的按鈕。

+0

是的,但如何消除這種疊加。 – Loyal

0

首先刪除已經存在的按鈕。您可以通過保留名稱或全局列表等方式或以其他方式跟蹤它們。當你輸入功能時,刪除之前存在的所有按鈕,然後創建新的按鈕。