To create an instance of a user control programmatically
-
In the user control, be sure that the directive contains a ClassName attribute that assigns a class to the user control.
The following example sets the ClassName attribute to strongly type a user control.
<%@ Control className="MyUserControl" %>
-
In the page where you want to work with the user control, create a reference to the user control with the directive.
When you create the user control programmatically, the strong type for your user control is available to the ASP.NET Web 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
You use the when you intend to load the control programmatically. You use the directive when you add a user control to the page declaratively. For details, see .
-
Create an instance variable for the user control, using the control's class name. The class will be part of the ASP namespace.
For example, if you want to create an instance of the user control declared as class Spinner, you use syntax such as the following:
VBProtected Spinner1 As ASP.Spinner
C#Protected ASP.Spinner Spinner1;
-
Create an instance of the user control in code by calling the method.
-
Assign property values as necessary, and then add the control to the collection of a container on the page, such as a control.
Note
When you add controls to the object using the 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 method and specify the index location where you want to store the control.
<%@ Page Language="C#" %><%@ Reference Control="~/Controls/Spinner.ascx" %>Load User Control Programmatically
reference: