ControlCollection.Add(Control) Method

Definition

Adds the specified Control object to the collection.

C#
public virtual void Add(System.Web.UI.Control child);

Parameters

child
Control

The Control to add to the collection.

Exceptions

The child parameter does not specify a control.

The ControlCollection is read-only.

Examples

The following code example uses the Add method to add a series of template items, the number of which are taken from the server control's view state, to a custom templated control.

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

The new control is added to the end of an ordinal index array. The control can be an instance of any ASP.NET server control, a custom server control you create, or a literal control.

To add a control to the collection at a specific index location, use the AddAt method.

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