如何:在运行时在一系列控件中添加或删除项

应用程序开发的常见任务是在窗体上的任何容器控件中添加控件或删除控件(如 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();  
       }  
    }  
    

另请参阅