2013-04-14 51 views
2

刪除按鈕之前,我產生我的程序按鈕,它應該通過清除它們:從動態數組

for (int i = 0; i < buttons.Length; i++) 
    this.Controls.Remove(buttons[i]); 

但是,所有這些從上一代按鈕保持。什麼可能導致這種情況?

(下面是全功能的,在其他功能上numButton變化。)

int numButtons = 5; 
    Button[] buttons = new Button[10]; 

    private void generate_buttons() 
    { 
     for (int i = 0; i < buttons.Length; i++) 
     { 
      this.Controls.Remove(buttons[i]); 
     } 
     for (int i = 0; i < numButtons; i++) 
     { 
      buttons[i] = new Button(); 
      buttons[i].Name = "btn" + i.ToString(); 
      buttons[i].Text = Convert.ToString(i + 1); 
      buttons[i].Size = new Size(40, 24); 

      int yOffset = 40; 
      int xOffset = 20 + i * 42; 
      buttons[i].Location = new Point(xOffset, yOffset); 
      buttons[i].BackColor = System.Drawing.SystemColors.Control; 
      buttons[i].Enabled = false; 
      buttons[i].Click += new EventHandler(this.clickMe); 
      buttons[i].Visible = true; 
      this.Height = yOffset + 104; 
      this.Width = xOffset + 75; 
     } 
     Controls.AddRange(buttons); 
    } 

回答

2

雖然你從控件集合刪除的按鈕,你不會從你的buttons陣列中刪除。添加

Array.Clear(buttons, 0, buttons.Length); 

我還修改了去除循環如圖所示here on MSDN由按鈕保存的所有資源的明確處理。

for (int i = 0; i < buttons.Length; i++) 
{ 
    //you can change break to 'continue' if you remove buttons 
    //from the array randomly so that if it encounters a null 
    //it will carry on reading the rest of the array. 
    if (buttons[i] == null) 
     break; 


    //dispose any button resources and event handlers so no references remain 
    buttons[i].Click -= new EventHandler(this.clickMe); 
    this.Controls.Remove(buttons[i]); 
    buttons[i].Dispose(); 
} 

Array.Clear(buttons, 0, buttons.Length); 

//.. 
+0

謝謝!這真的很有幫助。 – user1576628

-2

考慮使用泛型列表集合,而不是。這使您可以使用.Add()和.Remove()/。RemoveAt()方法更輕鬆地添加和刪除元素。

教程/例子:http://www.dotnetperls.com/list