4 Easy steps to create and consume .ACX web user controls in ASP.NET 4.0, Visual Studio 2010 SP1

What are ASP.NET Web User Controls?

Web User Controls are re-usable controls that you can create and use across multiple ASPX pages. When you need functionality in a control that is not provided by the built-in ASP.NET Web server controls such as
<asp:TextArea>, you can create your own controls.

User controls are containers into which you can put html markup and/or Web server controls such as <asp:textbox>. You can then treat the user control as a single unit and define properties and methods for it. These controls are visible to the user and typically are added to a asp web form.

In this post I’ll show you how to create simple user control that has three <asp:textbox> controls, one <asp:button> control and one <asp:Label> control. Also I’ll show you how to write the button_click event handler for this

User Control and how to embed this control on a web form.

Creating a New Web User Control in your Project using Visual Web Developer 2010 SP1

Right click on your project and choose Add/New Item. In the next dialog box, choose  Web User Control from the available list of Installed templates under Visual C#/Web.

ASP.NET Project Add New Item Menu

Adding Web User Control in Visual Studio 2010 SP1

It will create WebUserControl1.ascx, WebUserControl1.ascx.cs and WebUserControl1.ascx.designer.cs files and attach them to your project. Lets start with the ascx file.

What is an .ascx file ?

The .ascx file describes the ASP.NET Web user control. This is similar to a complete ASP.NET Web page (.aspx file), with both a user interface page and code. You create the user control in the same way you create an ASP.NET page and then add the markup and child controls that you need. A user control can include code to manipulate its contents like a page can, including performing tasks such as Page_Load()

Differences between a user controls file .ascx and ASP.NET Web page .aspx

  • The file name extension for the user control is .ascx where as ASP.NET page has .aspx extension.
  • Open the WebUserControl1.ascx.cs which is the codebehind for the ascx control. You will notice that the control inherits from the base class System.Web.UI.UserControl as opposed to System.Web.UI.Page for the ASP page.
  • Instead of an @ Page directive, the user control contains an @ Control directive that defines configuration and other properties.
  • User controls cannot run as stand-alone files.  You must add them to ASP.NET pages with .aspx extension.
  • The user control does not have html, body, or form elements in it. These elements must be in the hosting aspx page.

Now I’ll open the WebUserControl1.ascx and click on the design tab in the bottom to switch to design mode. I’ll add three text box controls from the toolbox on my left side. One for first name, one for last name and one for phone number. Also I added one Button and ane Label control .

Now double click on the Button to add an even handler for Button1_Click().

The .ascx file now looks like:

First Name<br />
<asp:TextBox ID="TextBox1" runat="server">
<br />Last Name<br />
<asp:TextBox ID="TextBox2" runat="server">
<br />Phone<br />
<asp:TextBox ID="TextBox3" runat="server">
<br /><br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Output">

I want to simply show the input field values in my Label when the button is clicked. Open the WebUserControl1.ascx.cs file and add the code for Button1_Click() as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ChalakiExamples {
    public partial class WebUserControl1 : System.Web.UI.UserControl    {
        protected void Button1_Click(object sender, EventArgs e)        {
            Label1.Text += "<br/>FN: " + TextBox1.Text + " LN: " + TextBox2.Text + " Phone: " + TextBox3.Text;

The WebUserControl1.ascx is now ready to be consumed by an ASP.NET aspx page.

Consuming the User Control I just created in a Web Forms Page

To use the user control just created, you need include it in an ASP.NET Web 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 performs. For more information about these processing stages, see ASP.NET Page Life Cycle Overview.

  1. In the containing ASP.NET Web page, create an @ Register directive that includes:
    1. A TagPrefix attribute, which associates a prefix with the user control. This prefix will be included in opening tag of the user control element.
    2. 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.
    3. A Src attribute, which defines the virtual path to the user control file that you are including.
    4. All the above steps can be achieved by simply dragging and droping the .ascx node from the project tree onto the ASP.NET aspx page (in design mode).
  2. In the body of the Web page, declare the user control element inside the form element.
    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ChalakiExamples.WebForm1" %><%@ Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"></asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <uc1:WebUserControl1 ID="WebUserControl11" runat="server" /></asp:Content>
  3. Optionally, if the user control exposes public properties, set the properties declaratively.

I’ll add one more item by clicking Add->New Item and from the templates I’ll choose “Web Form Using Master Page”.

Add New Item "WebForm Using Master Page"

It will ask me for the Master Page and I’ll use Site.master.

Selecting Master Page for a "Web Form Using Master page" Template

Let me first rename the WebForm1 to WebUserControlContainer. Now open the WebUserControlContainer.aspx in design mode and drag and drop the ascx node from the project onto the WebUserControlContainer.aspx page. You will immediately notice that all the five web controls that we placed into the user control are now visible in the aspx page.

WebForm with User Control In Design Mode

Now build the project and run the aspx page. You will see the web user control that you just created in action. All the three TextBox controls along with the Button Control and label control are visible on the web page. To test the control, type in the first name, last name and Phone Number and click Submit. You will see the Label refreshed with the values from the three TextBox controls as shown below:

Testing the WebUserControlContainer

We can create as many aspx web form pages as needed and by simply dropping the ascx control onto those pages we get the same functionality across all pages. That is the reuse-ability of the web user controls.

Managing State in User Controls across callbacks

User Controls, like ASPX pages can maintain state across callbacks, using the ViewState  member. The control’s ViewState member is an object of type StateBag, which is a sealed CSharp class provided by the ASP.NET framework (for those of you who are not sure what is a sealed class, it is CSharp class that prevents us to inherit/derive new classes by throwing compiler errors). Ok coming back to topic, we can use the ViewState object to store key/value pairs that persist across callbacks. For example you can assign ViewState["mykey"]=”My Value” in the Page_Load() function in the if (!IsPostBack) block and retrieve the value in the  if (IsPostBack) block of the Page_Load().

I am going to change my code in WebUserControl1.ascx.cs to show you how the state management works:

public partial class WebUserControl1 : System.Web.UI.UserControl {
        public string NumLoads = "";
        protected void Page_Load(object sender, EventArgs e) {
            if (IsPostBack){
                NumLoads = (int.Parse(ViewState["NumLoads"].ToString()) + 1).ToString();
                ViewState["NumLoads"] = NumLoads;
            else {
               NumLoads = "0";
                ViewState["NumLoads"] = NumLoads;
                Label1.Text += "<br/>ViewState[\"NumLoads\"]: " + NumLoads;
        protected void Button1_Click(object sender, EventArgs e){
             Label1.Text += "<br/>ViewState[\"NumLoads\"]: " + NumLoads +" FN: " + TextBox1.Text + " LN: " + TextBox2.Text + " Phone: " + TextBox3.Text;

Now run this aspx page, you will see that the NumLoads variable in the ViewState getting incremented by 1, every time you click on the button.

Output Caching of User Controls

Another neat feature of the user controls is they can be cached. In the .ascx file, you can declare the following OutputCache directive to cache this control for 10 sec.

<%@ OutputCache duration=”10″ varybyparam=”none” %>

If you want to set caching parameters in the code, you can do so by using an attribute in the user control’s class declaration. For example, if you include the following attribute in the metadata of your class declaration, a version of the content in the output cache is stored for 10 seconds.

public partial class WebUserControl1 : System.Web.UI.UserControl {
    // Class Code


ASP.NET Web User Controls feature lets you develop reusable web control components that can be used inside web forms. Once developed, they can be consumed by many web forms inside <form runat=”server”> blocks. User controls can manage their own state by using the ViewState object. User controls can also be output cached to reduce the load on the application server.

This entry was posted in ASP.NET, User Controls and tagged , , , , , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.