ASP.NET Web Forms Web Forms Server Controls Web Forms User Controls
Just as you can programmatically instantiate any Web Forms control on a page, you can also do so with user controls, using the Page.LoadControl method. When you do this, the ASP.NET runtime assigns the control a type based on its declarative file name following the pattern filename_extension. For example, if you save a user control as myUserControl.ascx
, the runtime will type the control as myUserControl_ascx. Because the LoadControl method returns a type of the Control class, it is important that you cast the user control to the appropriate strong type to set individual properties on the control.
NOTE: You can only strongly type a user control in a containing page by using the @ Register directive for the user control, whether in the containing page, or in the global configuration file. This is the case even if no user control tags are actually declared.
- Either in a code-behind file or in a code declaration block in an .aspx file, create a control instance, assign property values as necessary, and add the control to the Controls collection for this instance of the Page class. For example, in the following code, the myUserControl.ascx is instantiated with its BackColor property set to beige.
Control c1=LoadControl ( "myUserControl.ascx" );
( ( myUserControl_ascx ) c1 ) .BackColor="beige";
Page.Controls.Add ( c1 );
Introduction to User Controls Creating a User Control Including a User Control in Another Web Forms Page Defining Web Forms Event-Handling Methods Handling User Control Events