A good practice in ASP .NET and in programming in general is to divide the code into reusable blocks. This is applicable to HTML code too. In ASP .NET it is achieved by creating User Controls.
User controls look similar to web forms. They contain HTML and control tags, they are saved in .ascx files and they can also use some event handling logic. Some of the major differences between user controls and web forms are:

  • Their file extension is .ascx and not .aspx and it begins with “<%@ Control %>” directive instead of “<%@ Page %>“;
  • The files containing their event handling logic (if used) inherit from the System.Web.UI.UserControl class;
  • In order to be used by a web browser, user controls need to be embedded inside a web page;

An example of a simple user control code:

<%@ Control Language="C#" AutoEventWireup="true"
 CodeFile="Header.ascx.cs" Inherits="Header" %>
<asp:Label id="lblHeader" runat="server" />

In the example above, the attributes Language, AutoEventWireup and Inherits are the same as in a web page file.

Let’s add some logic behind this user control:

public partial class Header : System.Web.UI.UserControl
{
    protected void Page_Load(Object sender, EventArgs e)
    {
        lblHeader.Text = "Today is ";
        lblHeader.Text += DateTime.Today.DayOfWeek.ToString();
    }
} 

Upon page load, this code will add a text to the user conrtol’s label showing which day of the week it is now.

Using a user control in a web page

There are three ways for doing that.

  • The first one is to register the user control after the web page’s directive. This code ads a header in the form of user control to a page:
<%@ Page Language="C#" AutoEventWireup="true"
 CodeFile="PageWithHeader.aspx.cs" Inherits="PageWithHeader"%>
<%@ Register TagPrefix="apress" TagName="Header" Src="Header.ascx" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>A Page with a Header</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <apress:Header id="MyHeader" runat="server" />
        </div>
    </form>
</body>
</html>
  • The second one: instead of registering the user control in the web page file, developers can add it through the web.config xml:
<configuration>
    <system.web>
        <pages>
            <controls>
                <add tagPrefix="apress" src="~Header.ascx" tagName="Header" />
            </controls> 
        </pages>
    </system.web>
</configuration>

This way, developers can add as many user controls as they want and they will be available on all pages.

  • The third one is to create a user control during runtime: the Page class contains a method called LoadControl() which creates a user control during runtime using a .ascx file. The control is returned as object and can be inserted to a container control (ex. Panel) in the web page. Unless the goal is to alter the page interface dynamically, it is not advised to use this method because of its complexity.

Types of User Controls

  • Independent user controls: they are the simpler type and they do not interact with the other code on the form. The header control in this tutorial, so far, is an example of an independent user control.
  • Integrated user controls: they are the more complex type and they interact with the other page code. Usually this type of user control is implemented when developers need to determine the behaviour of the control through some properties. Let’s modify further our example making it an integrated user control. The user control will be the same – a header with a label in it that will display what day of the week currently is.

The first addition will be adding some more controls to our form:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<apress:Header id="MyHeader" runat="server" />
<body>
    <form id="form1" runat="server">
        <asp:RadioButtonList ID="ColorChooser" runat="server" OnSelectedIndexChanged="ColorChooser_SelectedIndexChanged">
            <asp:ListItem>Yellow</asp:ListItem>
            <asp:ListItem>Red</asp:ListItem>
            <asp:ListItem>Blue</asp:ListItem>
            <asp:ListItem Selected="True">Black</asp:ListItem>
        </asp:RadioButtonList>
        <asp:Label ID="ColorChooserLabel" runat="server" Text="Pick a color for the message above"></asp:Label>
        <p>
            <asp:Button ID="ColorSetter" runat="server" Text="Set color" />
        </p>
    </form>
</body>
</html>

The second one is modifying the class containing the logic behind the user control:

public partial class Header : System.Web.UI.UserControl
    {
        // Enum with available colors
        public enum HeaderColor
        { Yellow, Red, Blue, Black }

        private HeaderColor color = HeaderColor.Black;
        // Providing access to modify the color
        public HeaderColor Color
        {
            get { return color; }
            set { color = value; }
        } 

        protected void Page_Load(object sender, EventArgs e)
        {
            lblHeader.Text = "Today is ";
            lblHeader.Text += DateTime.Today.DayOfWeek.ToString();

            // Adding the logic changing the color of the header label
            if(color == HeaderColor.Yellow)
            {
                lblHeader.ForeColor = System.Drawing.Color.Yellow;
            }
            else if(color == HeaderColor.Red)
            {
                lblHeader.ForeColor = System.Drawing.Color.Red;
            }
            else if(color == HeaderColor.Blue)
            {
                lblHeader.ForeColor = System.Drawing.Color.Blue;
            }
            else
            {
                lblHeader.ForeColor = System.Drawing.Color.Black;
            }
        }
    }

And last – we add a class with logic for our web form:

public partial class MyForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (ColorChooser.SelectedValue == "Yellow")
            {
                MyHeader.Color = HeaderColor.Yellow;
            }
            else if (ColorChooser.SelectedValue == "Red")
            {
                MyHeader.Color = HeaderColor.Red;
            }
            else if (ColorChooser.SelectedValue == "Blue")
            {
                MyHeader.Color = HeaderColor.Blue;
            }
            else
            {
                MyHeader.Color = HeaderColor.Black;
            }
        }
    }

Here is what we get:

Fig 1: browser output

When the user selects a radio button from the radio button list and clicks on the button at the bottom, the color of the label in the header gets changed.

Was this post helpful?