Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

User Control In ASP.NET

User controls are one of ASP.NET methods to increase reusability of code, implement encapsulation and reduce maintenance. User control is similar to web page. Both web pages and user controls contain HTML elements and markup for web controls. Some tags, like <html>, <head> or <form> cannot be used in web user controls.

User controls are saved with .ascx extension, instead of .aspx for web pages. User controls can use code behind feature like web pages. Code behind file of web user controls ends with .ascx.cs. Markup code of user controls starts with @Control directive. Simplest web user control could contains only static HTML, like in this example:

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="WebUserControl.ascx.vb" Inherits="WebUserControl" %>
<p>Hello, I am very simple <b>web user control</b> with static HTML only.</p>

This web user control could be used when you need to repeat same code on many pages. Good examples are page footer, header or some kind of site navigation (depending of your case, it is good idea to consider using of Master Pages for this task as well). Except static HTML code, web user controls could contain web controls. You can simply drag and drop items from toolbox to user control. Like any other control, user controls can have properties, methods and events which make them very useful.

If user control solves more general problem, like progress bar or data pager control then can be useful on many different web sites. On this way, user controls can provide more stable and tested code.

How to create web user control

All user controls are derived from the System.Web.UI.UserControl class. UserControl and Page classes both inherits from TemplateControl class. You can add web user control to existing web site project, in Visual Studio menu go to WebSite -> Add New Item..., like in image bellow

Adding new user control in Visual Studio

New dialog will appear. To create new web user control, select web user control template, like in next image. Choose a name for your control and click Add.

Web user control template selected

How to add web user control to ASP.NET web page

To add web user control to web page, we need two lines. First, we need to register user control with Register directive on top of the page:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register tagprefix="bean" Tagname="footer" src="~/footer.ascx" %>

With Register directive we define user control on page. The important parameters are:

TagPrefix: prefix for user control tag. This prefix will be used in markup code later.

TagName: tag name of user control tag.

Src: path to .ascx file.

After registration with Register directive, you can place user control inside web form with tag formatted as <tagprefix:tagname, like this:

<bean:footer runat="server" id="MyUserControl" />

Registering user controls in web.config

If you'll use user control on many pages on web site then you can register control in web.config file. On this way you can use user control in complete web site without need to register it on every page. You can do this in <controls > section with code like this:

<configuration>
  <system.web>
    <pages>
      <controls>
        <add src="Footer.ascx" tagPrefix="bs" tagName="footer" />
      </controls >
    </pages >
  </system.web>
</configuration>

Dynamically loading web user controls

Although web user controls looks like a parts of web page, they are still "controls". You can add them to web page at design time, and also you can add web user controls at run time by using ASP.NET server side code and by using of some container. Container is usually PlaceHolder or Panel control. We can add user control dynamically with simple code like this:

[ C# ]

protected void Page_Load(object sender, EventArgs e)
{
// Declare user control variable
Control MyUserControl;
// Load user control dynamically
MyUserControl = LoadControl("UserControl1.ascx");
// Place user control in PlaceHolder control
MyPlaceHolder.Controls.Add(MyUserControl);
}

[ VB.NET ]

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Declare user control variable
Dim MyUserControl As Control
' Load user control dynamically
MyUserControl = LoadControl("UserControl1.ascx")
' Place user control in PlaceHolder control
myPlaceHolder.Controls.Add(MyUserControl)
End Sub

 

On this way, you can choose when and which control to load, based on user preferences, user or role rights etc. In detail guide how to load user controls dynamically you can read on Working with Web User Controls at Run-time tutorial.

Web user control properties and methods

We can add properties and methods to user control class like in code bellow:

[ C# ]

public void DoSomething()
{
  // Public method that do something great
}
// Public property
 public string FirstName
 {
     get
   {
     return lblFirstName.Text;
    }
   set
   {
     lblFirstName.Text = value;
    }
}

[ VB.NET ]

Public Sub DoSomething()
  ' Public method that do something great
End Sub

' Public property
Public Property FirstName() As String
   Get
    Return lblFirstName.Text
   End Get
  Set(ByVal value As String)
     lblFirstName.Text = value
   End Set
End Property

Web user control events

User control has predefined events like web page, so you don't need to learn anything new. There are Load, Init, PreRender, Error etc. events, used on the same way like in common web page:

[ C# ]

protected void Page_Load(object sender, EventArgs e) {
 
   // You can add code for user control events,
   // it looks like procedure for web page load
   // so you don't need to learn anything new
}

[ VB.NET ]

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 ' You can add code for user control events,
 ' it looks like procedure for web page load
 ' so you don't need to learn anything new
End
Sub

Custom events in user controls

Except predefined events, it is possible to declare your own events so your user control can notify the rest of application when something happen. Every event procedure use two parameters. First parameter is sender, the control that sent an event, and the second parameter is EventArgs object, or the custom class that inherits from System.EventArgs class. If we use custom class, we can add additional information that can be used in event procedure. But, in case that we have simple event, we can use generic EventArgs class.

You can create your own event in two simple steps. First, declare an event with code like this:

[ C# ]

public event EventHandler TitleChanged;

[ VB.NET ]

Public Event TitleChanged(ByVal sender As Object, ByVal e As EventArgs)

Second, inside some property or procedure, when certain circumstances occurs, you can raise an event with code like this:

[ C# ]

TitleChanged(this, EventArgs.Empty);

[ VB.NET ]

RaiseEvent TitleChanged(sender, e)

Web user control examples

Ok, enough about theory, we created two pretty useful examples of user controls. Maybe you can find them useful in some of your web projects.

First example is A simple Month Calendar Control which could be used for month selection when using of classic calendar control is inappropriate.

Month Calendar ASP.NET Control

Second example explains How to create ProgressBar user control when visitor expects to know a progress or current state of some operation.

Progress Bar ASP.NET Control

Conclusion

User controls could be very useful to save your time and avoid confusion. ASP.NET provides other types of controls, including custom server controls, components and web parts. Also there are a number of third party controls from independent software vendors. These controls are already well tested on many web sites and for small price can save you a lot of work. Third party controls are rarely created as user controls. Usually, they are compiled as custom server controls. Although user controls are easier to create, custom controls are easier to use. They can be placed on Visual Studio toolbox and act as standard built-in controls.


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   Google