2013-09-10 2 views
1

저는 C# Windows 양식을 사용하고있어 도움이 필요합니다. 나는 다른 버튼을 만들고 그것을 '버튼'목록에 추가하는 버튼이 있습니다. 내가 클릭 할 때 생성 된 각 단추를 자체 파괴해야합니다.동적으로 생성 된 단추 제거

 //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

클릭 이벤트 처리기는 object sender 이벤트의 소스 인 서명을

private void myButton_Click(object sender, EventArgs e)

있습니다. 그냥 Button에 그 캐스팅하고 클릭 무엇을 가지고있다 :

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

그러나이 메소드는 버튼이 아닌 어디서나 호출 할 수 있습니다. 확인하고 발신자가 버튼인지 확인하는 것이 좋습니다. –

+0

사실 충분합니다. 업데이트 됨. –

+0

이것은 완벽하게 작동했습니다! 위대한 도움이 사람, 감사합니다. – user2766605

0

보낸 사람 버튼입니다. 양식의 컨트롤 컬렉션에서 다음과 같이 제거 할 수 있습니다.

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