방법: 런타임에 컨트롤 컬렉션에서 컨트롤 추가 또는 제거

응용 프로그램을 개발할 때는 일반적으로 폼의 컨테이너 컨트롤(예: Panel이나 GroupBox 컨트롤 또는 폼 자체)에 컨트롤을 추가하거나 제거하는 작업을 하게 됩니다. 디자인 타임에는 컨트롤을 패널이나 그룹 상자로 직접 끌어 올 수 있으며, 런타임에는 이러한 컨트롤이 자체 컨트롤에 배치된 컨트롤을 추적하는 Controls 컬렉션을 관리합니다.

참고

다음 코드 예제는 자체 컨트롤에 배치된 컨트롤의 컬렉션을 관리하는 모든 컨트롤에 적용됩니다.

프로그래밍 방식으로 컬렉션에 컨트롤을 추가하려면

  1. 추가할 컨트롤의 인스턴스를 만듭니다.

  2. 새 컨트롤의 속성을 설정합니다.

  3. 컨트롤을 부모 컨트롤의 Controls 컬렉션에 추가합니다.

    다음 코드 예제에서는 Button 컨트롤의 인스턴스를 만드는 방법을 보여 줍니다. 이 예제를 실행하려면 폼에 Panel 컨트롤이 있어야 하며 만들어질 단추에 대한 이벤트 처리 메서드인 NewPanelButton_Click이 이미 있어야 합니다.

    Public NewPanelButton As New Button()
    
    Public Sub AddNewControl()
       ' The Add method will accept as a parameter any object that derives
       ' from the Control class. In this case, it is a Button control.
       Panel1.Controls.Add(NewPanelButton)
       ' The event handler indicated for the Click event in the code 
       ' below is used as an example. Substite the appropriate event
       ' handler for your application.
       AddHandler NewPanelButton.Click, AddressOf NewPanelButton_Click
    End Sub
    
    public Button newPanelButton = new Button();
    
    public void addNewControl()
    { 
       // The Add method will accept as a parameter any object that derives
       // from the Control class. In this case, it is a Button control.
       panel1.Controls.Add(newPanelButton);
       // The event handler indicated for the Click event in the code 
       // below is used as an example. Substite the appropriate event
       // handler for your application.
       this.newPanelButton.Click += new System.EventHandler(this. NewPanelButton_Click);
    }
    

프로그래밍 방식으로 컬렉션에서 컨트롤을 제거하려면

  1. 이벤트에서 이벤트 처리기를 제거합니다. Visual Basic에서는 RemoveHandler 문 키워드를 사용하고 Visual C#에서는 -= 연산자(C# 참조)를 사용합니다.

  2. Remove 메서드를 사용하여 패널의 Controls 컬렉션에서 해당 컨트롤을 삭제합니다.

  3. Dispose 메서드를 호출하여 해당 컨트롤에서 사용하던 모든 리소스를 해제합니다.

    Public Sub RemoveControl()
    ' NOTE: The code below uses the instance of 
    ' the button (NewPanelButton) from the previous example.
       If Panel1.Controls.Contains(NewPanelButton) Then
          RemoveHandler NewPanelButton.Click, AddressOf _ 
             NewPanelButton_Click
          Panel1.Controls.Remove(NewPanelButton)
          NewPanelButton.Dispose()
       End If
    End Sub
    
    private void removeControl(object sender, System.EventArgs e)
    {
    // NOTE: The code below uses the instance of 
    // the button (newPanelButton) from the previous example.
       if(panel1.Controls.Contains(newPanelButton))
       {
          this.newPanelButton.Click -= new System.EventHandler(this. 
             NewPanelButton_Click);
          panel1.Controls.Remove(newPanelButton);
          newPanelButton.Dispose();
       }
    }
    

참고 항목

참조

Panel

기타 리소스

Panel 컨트롤(Windows Forms)