asp.net.ph

Skip Navigation Links

Converting a Web Forms Page to a User Control

ASP.NET Web Forms   Web Forms Server Controls   Web Forms User Controls


If you have developed a Web Forms page and decide you would like to access its functionality throughout your application, you can make some minor alterations to the file to change it to a user control. Since the <html>, <body>, and <form> elements are not included in user controls, you must include these elements in the containing Web Forms page.

CAUTION: If you are developing a user control in a code-behind class, you must extend the UserControl class rather than the Page class. For more information, see Developing User Controls in a Code-Behind File.

To convert a Web Forms page into a user control

  1. Remove all <html>, <body>, and <form> elements from the page. The following example illustrates this conversion.
  • Initial Web Forms page:

<html>
<script language="C#" runat=server>
   void EnterBtn_Click ( object src, EventArgs e ) {
      Label1.Text = "Hi " +    Name.Text + " welcome to ASP.NET!";
   }
</script>

<body>
   <h3> Web Forms Page </h3>
   <form>
      Enter Name: <asp:textbox id="Name" runat=server/>
      <asp:button Text="Enter" OnClick="EnterBtn_Click"
runat=server/>
      <br><br>
      <asp:label id="Label1" runat=server/>
   </form>
</body>
</html>
  C# VB
  • The user control, following the conversion:

<h3> User Control </h3>

<script language="C#" runat=server>
   void EnterBtn_Click ( object src, EventArgs e ) {
      Label1.Text = "Hi " + Name.Text + " welcome to ASP.NET!";
   }
</script>

Enter Name: <asp:textbox id="Name" runat=server/>
<asp:button Text="Enter" OnClick="EnterBtn_Click"
runat=server/>
<br><br>
<asp:label id="Label1" runat=server/>
  C# VB
  1. If there is an @ Page directive in the Web Forms page, change it to an @ Control directive.

NOTE: To avoid parser errors when you convert a page to a user control, remove any attributes supported by the @ Page directive that are not supported by the @ Control directive. For more information, see Directive Syntax.

  1. Include a className attribute in the @ Control directive. This allows the user control to be strongly typed when it is added to a page or other server controls programmatically.
  2. Give the control a file name that reflects how you plan to use it and change the file name extension from .aspx to .ascx.

See Also

Including a User Control in a Web Forms Page   Creating a User Control   Defining Web Forms Event-Handling Methods   Handling User Control Events



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note