How to: Add to or Remove from a Collection of Controls at Run Time


Common tasks in application development are adding controls to and removing controls from any container control on your forms (such as the Panel or GroupBox control, or even the form itself). At design time, controls can be dragged directly onto a panel or group box. At run time, these controls maintain a Controls collection, which keeps track of what controls are placed on them.


The following code example applies to any control that maintains a collection of controls within it.

To add a control to a collection programmatically

  1. Create an instance of the control to be added.

  2. Set properties of the new control.

  3. Add the control to the Controls collection of the parent control.

    The following code example shows how to create an instance of the Button control. It requires a form with a Panel control and that the event-handling method for the button being created, NewPanelButton_Click, already exists.

    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.
       // 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);

To remove controls from a collection programmatically

  1. Remove the event handler from the event. In Visual Basic, use the RemoveHandler Statement keyword; in Visual C#, use the -= Operator (C# Reference).

  2. Use the Remove method to delete the desired control from the panel's Controls collection.

  3. Call the Dispose method to release all the resources used by the control.

    private void removeControl(object sender, System.EventArgs e)
    // NOTE: The code below uses the instance of 
    // the button (newPanelButton) from the previous example.
          this.newPanelButton.Click -= new System.EventHandler(this.