This documentation is archived and is not being maintained.

Including a User Control in a Web Forms Page

User controls work only when they are included in a Web Forms page. When a request arrives for a page and that page contains a user control, the user control goes through all of the processing stages that any ASP.NET server control is subject to. For more information about these processing stages, see Web Forms Page Processing.

Including a user control in a Web Forms page is simple.

To include a user control in a Web Forms page

  1. In the containing Web Forms page, declare an @ Register directive that includes:
    • A tagprefix attribute, which associates a prefix with the user control. This prefix will be included in opening tag of the user control element.
    • A tagname attribute, which associates a name with the user control. This name will be included in the opening tag of the user control element.
    • A Src attribute, which defines the virtual path to the user control file that you are including in the Web Forms page.
      Note   The Src attribute value can be either a relative or an absolute path to the user control source file from your application's root directory. For ease of use, it is recommended you use a relative path. The tilde (~) character represents the root directory of the application.

    For example, the following code registers a user control defined in the file Login1.ascx. It has been given the tag prefix Acme and the tag name Login. The file is located in a Controls directory.

    <%@ Register TagPrefix="Acme" TagName="Login" Src="~\controls\login1.ascx" %>
  2. Using custom server control syntax, declare the user control element between the opening and closing tags of the HtmlForm server control (<form runat=server></form>). For example, to declare the control imported in the previous step, use the following syntax.
    <form runat="server">
    <Acme:Login id="MyLogin" runat="server"/>
    Note   Regardless of how many ASP.NET server controls (user controls and any others) you include on your Web Forms page, you should include only one HtmlForm server control on a Web Forms page. Include all server controls between the opening and closing tags of this control.

See Also

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