操作說明:在執行階段時從控制項集合新增或移除

應用程式開發中的常見工作是將控制項新增至表單上,並從表單上的任何容器控制項移除控制項(例如 PanelGroupBox 控制項,甚至是表單本身)。 在設計階段,可以將控制項直接拖曳至面板或群組方塊。 在執行階段,這些控制項會維護 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. Substitute the appropriate event  
       // handler for your application.  
       this.newPanelButton.Click += new System.EventHandler(this. NewPanelButton_Click);  
    }  
    

以程式設計方式移除集合中的控制項

  1. 移除事件的事件處理常式。 在 Visual Basic 中 ,使用 RemoveHandler Statement 關鍵字;在 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();  
       }  
    }  
    

另請參閱