2013-09-10 87 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); 
}