Web User Controls can be used in ASP.NET to allow developers to create complex controls and reuse them in multiple places. For instance, if we were making a website in which you needed a particular form in more than one place, you could add the form to the Web User Control and then add that to multiple different pages easily.

Creating a Web User Control

At this point in the tutorial I have created a new ASP.NET Empty Web Site. What we need to do first is add a new Web User Control to the project, to do this:

  1. Right click the project in your Solution Explorer.
  2. Select Add New Item…
  3. Select a Web User Control.
  4. Name it ContactForm.ascx.
  5. Click Add.

Next, we need to add some controls onto the Web User Control. Because we are not going to create any sort of functionality in here, I’m going to keep it simple and just add in a TextBox and a Button. To do this, open ContactForm.ascx up to Design mode and:

  1. Drag and drop a TextBox onto the Web User Control.
  2. To the right of the TextBox hit Enter to create a line break.
  3. Drag and drop a Button onto the Web User Control under the TextBox.

Adding the Web Form

Next, we need to add a Web Form to the project that we will add our Web User Control to. To do this:

  1. Right click the project in your Solution Explorer.
  2. Select Add New Item…
  3. Select a Web Form.
  4. Name it Default.aspx.
  5. Click Add.

What we are going to do now is demonstrate two different ways to add the Web User Control to the Web Form. First, to add it in ASP open the Default.aspx up to Source mode and:

At the top of the file, underneath the <%@ Page %> code, add in the following to register the Web User Control:

In the div tags of the body, add in the following:

What this has done is registered our user control as WebUserControl:WebTag and then created an instance of it on the Web Form.

The second way we can add the Web User Control is in the C# codebehind. To do this, open up the Default.aspx.cs codebehind file for editing and add the following code to the Page_Load event method:

Download Source Files