如何:在运行时向控件集合中添加或删除控件

应用程序开发中的常见任务是向窗体上的任何容器控件添加控件以及从控件中删除控件(例如 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 语句 关键字;在 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();  
       }  
    }  
    

另请参阅