Click here to Skip to main content
15,868,016 members
Articles / Web Development / ASP.NET

User controls in ASP .NET

Rate me:
Please Sign up or sign in to vote.
4.78/5 (55 votes)
15 Jan 2002CPOL5 min read 879.8K   9.2K   105   64
An introduction to writing User Controls in ASP .NET

Introduction

In traditional ASP code reuse and encapulation was traditionally done using a combination of include files and web classes. While this worked reasonably well for business logic, it was always a little fiddly for visual components. For example, if you wanted to display a grid of data in many different places and have the grid have the same general look and feel, but be customisable for a particular page, then you either cut and pasted the HTML, used style sheets, used an include file, wrote some VBScript to generate the HTML on the fly, or used a combination of all these methods.

It was messy. It could also be difficult to move these components between projects because there was the ever present problem of ensuring that variable names didn't conflict, that you had the include file included only once (and in the correct order). Then there was the whole issue of tying the new control into existing code.

ASP .NET solves many of these issues with the introduction of User Controls. These are self contained visual elements that can be placed on a web page in the same way as a tradition intrinsic HTML control, and can have their attributes set in a similar fashion.

In this article I'll present a Title bar that has 6 properties (border width and colour, Title text and colour, background and padding. The control is embedded in a page using the following simple syntax:

<CP:TitleBar Title="User Control Test" TextColor="green" Padding=10 runat=server />

This produces the following output:

Sample Image - MyUserControl.gif

So how do we write a user control?

The easiest way is using Visual Studio .NET. Start a new web project and right click on the project's name in the Server Explorer. Select 'Add...' then 'Add Web User Control...' Rename the control and hit Open. The wizard produces two files: a .ascx file containing the visual layout, and a .ascx.cs (assuming you are working in C#) that has the business logic.

The Visual Layout

First we design the visual layout of the Title bar. We'll use the new asp:XXX controls so that we get simple access to their attributes at runtime.

The entire .ascx file looks like:

<%@ Control Language="c#" AutoEventWireup="false" 
    Codebehind="MyUserControl.ascx.cs" 
    Inherits="CodeProject.MyUserControl" 
    TargetSchema="http://schemas.microsoft.com/intellisense/ie3-2nav3-0"%>

<asp:table id=OuterTable BackColor=#c0c0c0c BorderWidth=0 cellPadding=0 
           cellSpacing=1 width='100%' Runat=server>
<asp:tableRow><asp:tableCell width="100%">

<asp:table id=InnerTable BackColor=#cccccc BorderWidth=0 cellPadding=0 
           cellSpacing=1 width="100%" Runat=server>
<asp:tableRow<asp:tablecell HorizontalAlign=Center>

<asp:Label ID=TitleLabel Runat=server />

</asp:tablecell></asp:tableRow>
</asp:table>

</asp:tablecell></asp:tableRow>
</asp:table>

A fairly traditional way of creating a table with a thin border - except that we are using ASP .NET controls instead of traditional HTML.

Note that if you were restricting your viewers to using IE then you could use the border-width style to set the border style and stick with one table. However, if you have Netscape 4.X viewers then this won't work. ASP .NET controls will output HTML 3.2 for downspec browsers like Netscape, so while ASP .NET's promise of 'write-once, view anywhere' sounds good, it doesn't actually happen in practice.

I'm not going to go into the in's and out's of ASP .NET controls. They are fairly self explanatory. Just make sure you include the 'runat=server' bit. They help.

The backend logic

Note the bit up the top of the file: Codebehind="MyUserControl.ascx.cs". This is where the visual layout (.ascx file) is hooked up with the backend logic (.ascx.cs). We will barely scrape the surface of what this separation of logic and display can do.

Our C# code looks like the following:

namespace CodeProject
{
    using System;
    ...

    public abstract class MyUserControl : System.Web.UI.UserControl
    {
        public string Title       = null;
        public string TextColor   = Color.Black.Name;
        public string BackColor   = Color.Wheat.Name;
        public int    Padding     = 2;
        public string BorderColor = Color.Gray.Name;
        public int    BorderWidth = 1;
        
        protected Table OuterTable;
        protected Table InnerTable;
        protected Label TitleLabel;

        private void Page_Load(object sender, System.EventArgs e)
        {
            if (Title==null || Title=="") 
                Visible = false;
            else
            {

                OuterTable.BackColor   = Color.FromName(BorderColor);
                OuterTable.CellSpacing = BorderWidth;
                InnerTable.CellPadding = Padding;
                InnerTable.BackColor   = Color.FromName(BackColor);
                
                TitleLabel.Text        = Title;
                TitleLabel.ForeColor   = Color.FromName(TextColor);
                TitleLabel.Font.Name   = "Verdana";
                TitleLabel.Font.Bold   = true;
                TitleLabel.Font.Size   = FontUnit.Parse("13");
            }
        }

        #region Web Form Designer generated code
        ...
        #endregion
    }
}

The entire purpose of this backend is to define a set of properties that the user can access when instantiating the control, and to then set the attributes of the ASP .NET controls in our .ascx file based on these properites.

We could just as easily open a connection to a database and bind a dataset to a control, or we could access the page that this control resides in (using the Page property) and adjust the look and feel of the control from what we find there. We could also provide user input mechanisms in our display and provide handlers for click events in the control here as well. These controls really are quite powerful.

Unfortunately we'll be staying a lot closer to Earth and will only provide the mediocrity of colour and border width changes.

Properties

Note the block of variable declarations at the top:

public string Title       = null;
public string TextColor   = Color.Black.Name;
public string BackColor   = Color.Wheat.Name;
public int    Padding     = 2;
public string BorderColor = Color.Gray.Name;
public int    BorderWidth = 1;

These publicly accessible variables form the attributes that are available to the user when he or she instantiates the control in a web page:

<CP:TitleBar Title="User Control Test" TextColor="green" Padding=10 runat=server />

The user can set all, some or none of these properties.

The link between the visual elements and the code

The other half of the story is the link between the ASP .NET controls and the C# code. Note the block of variables underneath these:

protected Table OuterTable;
protected Table InnerTable;
protected Label TitleLabel;

The names of these variables are the same as the ID's of the ASP .NET controls in our .ascx page. This causes the variable in our C# class to be linked up to the ASP .NET control in the .ascx page. We can now manipulate the controls on the page however we like:

if (Title==null || Title=="")
    Visible = false;
else
{

    OuterTable.BackColor   = Color.FromName(BorderColor);
    OuterTable.CellSpacing = BorderWidth;
    InnerTable.CellPadding = Padding;
    InnerTable.BackColor   = Color.FromName(BackColor);

    TitleLabel.Text        = Title;
    TitleLabel.ForeColor   = Color.FromName(TextColor);
    TitleLabel.Font.Name   = "Verdana";
    TitleLabel.Font.Bold   = true;
    TitleLabel.Font.Size   = FontUnit.Parse("13");
}

Here we simply check if there is any title text, and if not then we set the control as invisible (meaning the HTML for the control simply won't be rendered and will not be sent down to the client). If there is text then we go ahead and set the properties of the controls.

And we're done!

Using the control

To use the control you will first need to compile the project with your files, and then create a page to host the control. The code for the control will be compiled into an assembly and placed in the /bin directory. If you make any changes to the C# code you'll need to recompile. You do not have to recompile if you make changes to the visual layout (.ascx) file.

To use the control you must make a page aware of the control. We do this by using a Register directive that specified the tag prefix we'll use, the tag name and the location of the user control's page:

<%@ Register TagPrefix="CP" TagName="TitleBar" Src="MyUserControl.ascx" %>
         
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 
<html>
  <head>
    <title>MyPage</title>
  </head>
  <body>
  <basefont face=verdana>
  
  <CP:TitleBar Title="User Control Test" TextColor="green" Padding=10 runat=server />
    
  </body>
</html>

The tag prefix in this case is CP, and the tag TitleBar They can be anything you want as long as there are no conflicts. Open the page in your browser and be amazed at your cleverness.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder CodeProject
Canada Canada
Chris Maunder is the co-founder of CodeProject and ContentLab.com, and has been a prominent figure in the software development community for nearly 30 years. Hailing from Australia, Chris has a background in Mathematics, Astrophysics, Environmental Engineering and Defence Research. His programming endeavours span everything from FORTRAN on Super Computers, C++/MFC on Windows, through to to high-load .NET web applications and Python AI applications on everything from macOS to a Raspberry Pi. Chris is a full-stack developer who is as comfortable with SQL as he is with CSS.

In the late 1990s, he and his business partner David Cunningham recognized the need for a platform that would facilitate knowledge-sharing among developers, leading to the establishment of CodeProject.com in 1999. Chris's expertise in programming and his passion for fostering a collaborative environment have played a pivotal role in the success of CodeProject.com. Over the years, the website has grown into a vibrant community where programmers worldwide can connect, exchange ideas, and find solutions to coding challenges. Chris is a prolific contributor to the developer community through his articles and tutorials, and his latest passion project, CodeProject.AI.

In addition to his work with CodeProject.com, Chris co-founded ContentLab and DeveloperMedia, two projects focussed on helping companies make their Software Projects a success. Chris's roles included Product Development, Content Creation, Client Satisfaction and Systems Automation.

Comments and Discussions

 
QuestionBuild error , code is not working. Pin
Member 103490034-Aug-16 1:48
Member 103490034-Aug-16 1:48 
AnswerRe: Build error , code is not working. Pin
Chris Maunder28-Oct-16 5:21
cofounderChris Maunder28-Oct-16 5:21 
GeneralHi Pin
Cipherc19-Dec-15 9:17
Cipherc19-Dec-15 9:17 
GeneralRe: Hi Pin
Chris Maunder19-Dec-15 13:58
cofounderChris Maunder19-Dec-15 13:58 
Questionhow to add this from code behind? Pin
xinwater200118-Mar-15 3:40
xinwater200118-Mar-15 3:40 
GeneralThanks For your sample Pin
cheng.john11-Nov-14 23:05
cheng.john11-Nov-14 23:05 
GeneralMy vote of 1 Pin
Balasubramanian T23-Sep-13 19:52
Balasubramanian T23-Sep-13 19:52 
GeneralMy vote of 2 Pin
Member 95240117-Mar-13 0:04
Member 95240117-Mar-13 0:04 
GeneralMy vote of 3 Pin
Abhisheik yk1-Jan-13 22:07
Abhisheik yk1-Jan-13 22:07 
QuestionExcellent post! Pin
Minghang22-Sep-12 7:04
Minghang22-Sep-12 7:04 
GeneralMy vote of 5 Pin
bajwa0135-Jul-12 1:48
bajwa0135-Jul-12 1:48 
GeneralIt give build Error ! Pin
Mr Ashish Anand3-Jun-11 2:01
Mr Ashish Anand3-Jun-11 2:01 
GeneralMy vote of 2 Pin
Member 323281315-Feb-11 22:07
Member 323281315-Feb-11 22:07 
GeneralUser Control Pin
MathewPV3-Nov-10 19:58
MathewPV3-Nov-10 19:58 
GeneralMy vote of 2 Pin
tmslvn13-Oct-10 16:50
tmslvn13-Oct-10 16:50 
GeneralMy vote of 5 Pin
Member 33082472-Jul-10 9:47
Member 33082472-Jul-10 9:47 
GeneralThanks Pin
Tom Klein13-Jul-09 22:32
Tom Klein13-Jul-09 22:32 
QuestionHelp register user control Pin
Nitin Kr Jain15-May-08 2:33
Nitin Kr Jain15-May-08 2:33 
GeneralSweet Pin
extremeg21-Feb-08 21:49
extremeg21-Feb-08 21:49 
QuestionIs there a VB version of this code? Pin
Veeves23-Feb-06 4:30
Veeves23-Feb-06 4:30 
The code in this article is Greek to me.
AnswerRe: Is there a VB version of this code? Pin
Tom Klein13-Jul-09 22:33
Tom Klein13-Jul-09 22:33 
GeneralDisplaying User Control without overlapping Pin
rajabunny13-Jul-05 17:53
rajabunny13-Jul-05 17:53 
GeneralRe: Displaying User Control without overlapping Pin
TicTac2Kcal2-Aug-05 21:39
TicTac2Kcal2-Aug-05 21:39 
GeneralI know I'm making this harder than it needs to be. Pin
Chuck Lane8-Jul-04 10:39
Chuck Lane8-Jul-04 10:39 
GeneralUserControl prop from code-behind of parent page Pin
colinhodges26-Apr-04 18:43
colinhodges26-Apr-04 18:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.