Tip #87: Did you know… How to reuse a web page by converting into an ASP.NET User Control?

If you want to reuse a web form's content in other places in your application, you can easily convert the page into an ASP.NET User Control. Then you can add that user control to any other page.

For example, you have a page in your application that looks like the following:

WebForm

 

Now, you need to rename to the file to have a .ascx extension. Then remove html, head, body, form tags from the page. Change the "@ Page" directive to a "@ Control" directive.  Remove all attributes of the "@ Control" directive, except Language, AutoEventWireup, CodeFile, and Inherits. You also need the change the Inherits to have your new UserControl code behind file's name, like in the image below. Close and re-open the file to make squiggles go away.

MyUserControl 

 

If you have a code-behind file, its name will be changed properly for you automatically. Open the file and change the class it inherits from to UserControl, and the class name to match your .ascx file. See below.

MyUserControlCodeBehind

More information can be found here.