This documentation is archived and is not being maintained.

Creating Instances of User Controls Programmatically

Just as you can programmatically create an instance of any ASP.NET server control on a Web Forms page, you can do the same with user controls by using the containing page's LoadControl method. First, however, you must associate a strong type with the user control by using the className attribute on the @ Control directive. This is necessary because the LoadControl method returns a type of the Control class, and you need to cast the user control to the appropriate strong type to be able to set individual properties on the control.

The following example uses the className attribute to strongly type a user control saved in the file MyUserControl.ascx.

<%@ Control className="MyUserControl" %>

To create an instance of a user control programmatically

  1. Register the user control at the top of the containing Web Forms page with the @ Reference directive. When you create the user control programmatically, the strong type for your user control is available to the Web Forms page only after you have created a reference to it. For example, the following code creates a reference to a user control created in the MyUserControl.ascx file.
    <%@ Reference Control="MyUserControl.ascx" %>
    Note   When creating instances of a user control declaratively in a Web Forms page, use the @ Register directive.
  2. Create an instance of the user control, either in the code-behind class file or the code declaration block for the containing .aspx file. Assign property values as necessary, and add the control to the containing page's ControlCollection object using the Add method. This is made available to the page's inherited Control.Controls property. In the following example, an instance of MyUserControl.ascx is created with its BackColor property set to beige.
    Dim c1 As UserControl = LoadControl("MyUserControl.ascx")
    CType(c1, MyUserControl).BackColor = "beige"
    Control c1 = LoadControl("MyUserControl.ascx");
    ((MyUserControl)c1).BackColor = "beige";
    Note   When you add controls to the ControlCollection object using the Add method, they are placed in the collection in the order they are processed. If you want to add a control to a specific position in the collection, use the AddAt method and specify the index location where you want to store the control.

See Also

Web Forms User Controls | Creating a User Control | Including a User Control in Another Web Forms Page | Server Event Handling in Web Forms Pages | Handling User Control Events