2013-09-10 86 views
1

我正在使用C#窗體並需要一些幫助。我有一個按鈕可以創建其他按鈕並將它們添加到列表的「按鈕」中。我需要讓每個按鈕在點擊時自行銷燬。刪除動態生成的按鈕

 //create new button 
     Button newButton = new Button(); 
     newButton.Name = "aButt"+buttNum; 
     Debug.WriteLine(newButton.Name); 
     buttNum++; 

     newButton.Text = "Button!"; 
     newButton.Height = 50; 
     newButton.Width = 50; 

     //controls where the new button gets placed 
     if (curX > 9) 
     { 
      curX = 0; 
      curY++; 
      //defines the point the button spawns 
      newButton.Location = new System.Drawing.Point((curX * 55)+10, curY * 55); 
      //increments X to avoid placing a button on top of another 
      curX++; 

     } 
     else 
     { 
      newButton.Location = new System.Drawing.Point((curX * 55) + 10, curY * 55); 
      curX++; 
     } 


     newButton.UseVisualStyleBackColor = true; 
     newButton.Click += new System.EventHandler(this.removeThisButton); 
     buttons.Add(newButton); 
     this.Controls.Add(newButton); 

我有事件監聽器的設置,但由於發件人沒有關於按鈕本身的實際信息,我不知道如何擺脫它。

任何幫助表示讚賞!

+0

這是一個Windows Forms應用程序嗎? WPF?我想添加更多特定標籤來吸引專家。 – neontapir

回答

2

Click事件處理程序有簽名

private void myButton_Click(object sender, EventArgs e)

object sender是事件的源頭。只投這一個Button,而且也得到了點擊的內容:

Button whatWasClicked = sender as Button; 
    if(whatWasClicked == null) 
     // never mind -- it wasn't a button... 
+0

但是,您可以從任何地方調用此方法,而不一定是按鈕。這將是很好的檢查並確保發件人是按鈕。 –

+0

夠正確。更新。 –

+0

這工作完美!幫助很大的人,謝謝。 – user2766605

0

發件人按鈕。您可以從Form的控件集合中移除它,如下所示:

private void removeThisButton(object sender, EventArgs e) { 
    this.Controls.Remove(sender); 
}