ControlCollection.Clear Method

Definition

Removes all controls from the current server control's ControlCollection object.

C#
public virtual void Clear();

Examples

The following code example demonstrates overriding the Control.CreateChildControls method, and using the Clear method to delete all child controls previously in the ControlCollection object. In this case, you must do this so that outdated objects in your control's ControlCollection are not displayed inappropriately.

C#
// Override to create repeated items.
protected override void CreateChildControls() {
    object o = ViewState["NumItems"];
    if (o != null) {
       // Clear any existing child controls.
       Controls.Clear();

       int numItems = (int)o;
       for (int i=0; i < numItems; i++) {
          // Create an item.
          RepeaterItem item = new RepeaterItem(i, null);
          // Initialize the item from the template.
          ItemTemplate.InstantiateIn(item);
          // Add the item to the ControlCollection.
          Controls.Add(item);
       }
    }
}

Remarks

Use this method to empty a custom control's ControlCollection when you override the Control.CreateChildControls and DataBind methods. Do this when you develop composite, templated controls or templated data-bound controls.

Applies to

Product Versions
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

See also