Creating User Controls Programmatically
Just as ordinary server controls can be created programmatically, so user controls can be. The page's LoadControl method is used to
load the user control, passing the virtual path to the user control's source file:
Dim c1 As Control = LoadControl("pagelet7.ascx")
CType(c1, (Pagelet7VB)).Category = "business"
Page.Controls.Add(c1)
VB
The type of the user control is determined by a ClassName attribute on the Control directive. For
example, a user control saved with the file name "pagelet7.ascx" is assigned the strong type "Pagelet7CS"
as follows:
<%@ Control ClassName="Pagelet7CS" %>
Because the LoadControl method returns a type of System.Web.UI.Control, it must be cast to the
appropriate strong type in order to set individual properties of the control. Finally, the user
control is added to the base page's ControlCollection.
Important The strong type for a user control is available to the containing Web Forms page only if a Register directive is included for
the user control (even if there are no user control tags actually declared).
- User controls allow developers to easily define custom controls using the same programming techniques as for writing Web Forms pages.
- As a matter of convention, an .ascx file name extension is used to indicate such controls. This ensures that a user control file cannot
be executed as a standalone Web Forms page.
- User controls are included into another Web Forms page using a Register directive, which specifies a TagPrefix, TagName, and Src location.
- After the user control has been registered, a user control tag may be placed in a Web Forms page as an ordinary server control (including the runat="server" attribute).
- The public fields, properties, and methods of a user control are promoted to public properties (tag attributes) and methods of the
control in the containing Web Forms page.
- User controls participate in the complete execution lifecycle of every request and can handle their own events, encapsulating some of the
page logic from the containing Web Forms page.
- User controls should not contain any form controls but should instead rely on their containing Web Forms page to include one if necessary.
- User controls may be created programmatically using the LoadControl method of the System.Web.UI.Page class. The type of the user control is
determined by the ASP.NET runtime, following the convention filename_extension.
- The strong type for a user control is available to the containing Web Forms page only if a Register directive is included for
the user control (even if there are no user control tags actually declared).
Copyright 2001-2002 Microsoft Corporation. All rights reserved.