Publish Article
Go Freelance

How to write UserControls In ASP.Net


If you are seeing this section and do not see download links, this means that you are not logged into our site. If you already are a member, click on the login link and login into site and come back to this page for downloading the control files. If you are not a member, click on registration link to become a Winista member and download the control for free.

During the development a web site, we always wonder is there an easy way to templatize the common user interface tasks into a control that can be reused or just included in the web page by simply making use of some kind of include mechanism. In classic we all used to accomplsih this by either writing some ASP components or put the commonly used code in a script file and later on include these files using the server-side include feature of Internet Information Server (IIS).

But we all know how painful this process is without knowing before hand how this UI control is going to look like. Or how the layout is going to look like. There are couple of ways that most of the developers followed. The one that was very common is use some kind of WYSIWYG kind of web editors. The leading in these categories are Visual Interdev, Front Page, Dreamweaver or some other share ware products. After generating the layout, take the HTML code and put in a file or ASP component and then include it in the web page. Or the other option was, just trust your judgement and start writing the component layout programatically and then later on fix it up during debugging.

With ASP.Net, all this pain and agony has been relieved. There is a very clean and effective technique to accomplish these tasks. ASP.Net provides mechanism of writing UserControls which are very much like ASP.Net web-form pages with the following differences.

  • These files have .ascx extension and not .aspx
  • You don't need to provide <html>, <body> and <form> tags that qyalify a page as a web page.

UserControls offer the following features.

  • Write the common UI features of your web applications as reusable components. And this reusabilty is not just limited to one application. Properly written user controls can be distributed for usee in other web applications too.
  • Unlike classic ASP includes, the UserControls are not interpreted for every request. They get cached after the first invocation. This helps in speeding up the response of your web pages.
  • UserControls use the same object model as an ASP.Net was page (with extension .aspx). So it gives a great flexibility in terms of using the event model of the ASP.Net web server controls and controlloing the execution at run time.
  • UserControls can be cached independent of rest of the web page. This technique is called "fragment caching". It also helps in speed up loading of pages.

As you can see, UserControls provide a lot more fexibility and power than the classic ASP SSI. This article is first in the series of demonstrating how you can write UserControls for accomplishing common tasks and then later on using it through out the web site.

SiteFooter Control

This is first of the UserControls that we have developed for our web site. Every web site out there has some kind of footer onm every page and so do we. Therefore we decided to demonstrate the concept of UserControls in developing this very simple control. Following are the simple steps that we followed to write this control.

  • Create blank file, SiteFooter.ascx, using the VS.Net editor. Note that we did not use "Add Web User Control" wizard for this.
  • Declare the @Control directive at the top of the page. This is very important. This directive defined at the top of the file tells ASP.Net framework that this is an UserControl.
    <%@ Control CodeBehind="SiteFooter.ascx.cs" Language="c#"
     AutoEventWireup="false" Inherits="ASPNet_App.Controls.SiteFooter" >
    Notice the various attributes defined within the @Control directive. We would describe some of these attributes. For more details, take a look at the .NET framework documentation.
    • CodeBehind - This attribute specifies the file that contains the code-behind source for the control. If you don't intend to use any code for the control, it is not mandatory to define this attribute.
    • Language - Specifies the server side language that will be used to compile the source code.
    • EnableViewState - This is a very important attribute that you can set either delartively or programtically. If your control does not need to save any state between post backs then make sure that it is set to false. This saves is one more to optimize the rendering speed of web pages.
  • After declaring the @Control directive, just start adding the controls to the file in the the layout that you want to use for your web site. For example for our site, we decided to have two rows of links to various general information pages, so we added two Panel controls that get rendered as two <div> tags.
  • Now the control is ready to be included in the web pages. You can see how easy it was to write this UserControl.
	<asp:Panel ID="FooterPanel" Runat="server">
		<asp:Panel id="FirstLineControls" Runat="server">
			<asp:HyperLink id="GoHome" Runat="server" CssClass="footerLink"
			<asp:HyperLink id="AboutUs" Runat="server" CssClass="footerLink"
				NavigateUrl="#">About Us</asp:HyperLink> 
			<asp:HyperLink id="ContactUs" Runat="server" CssClass="footerLink"
				NavigateUrl="#">Contact Us</asp:HyperLink> 
			<asp:HyperLink id="Questions" Runat="server" CssClass="footerLink"
			<asp:HyperLink id="SiteMap" Runat="server" CssClass="footerLink">
				Site Map</asp:HyperLink>
		<asp:Panel id="SecondLineControls" Runat="server">
			<asp:HyperLink id="Copyright" Runat="server" CssClass="footerLink"
			<asp:HyperLink id="Privacy" Runat="server" CssClass="footerLink"
				NavigateUrl="#">Privacy Policy</asp:HyperLink> 
			<asp:HyperLink id="Shipping" Runat="server" CssClass="footerLink"
				NavigateUrl="#">Shipping Policy</asp:HyperLink> 
			<asp:HyperLink id="Return" Runat="server" CssClass="footerLink"
				NavigateUrl="#">Return Policy</asp:HyperLink>

SiteCopyright Control

This is the second control we have written for a simple demonstration. But it is one common UI feature that every web site has. All web sites display a Copyright notice and everybody has a diferent format but it is the same for a web site. When I say the format is same for a web-site, we are talking about well designed web sites that keep the look and feel the same from page to page.

We decided to write a very simple UserControl for our web site. What id does is nothing fancy schmancy. It simple displays one line of text displaying the site's Copyright notice. The difference between this control and the eralier, SiteFooter, control is that it uses Page_Load event to change the style attributes of Label control at run time. It displays that UserControl also follow the event mechanism that is used for loading pages and server controls.

<%@ Control Language="c#" AutoEventWireup="false" Codebehind="SiteCopyright.ascx.cs"
<asp:Panel ID="CopyRightPanel" Runat="server">
	<asp:Label id="CopyRightLabel" Runat="server">
		Copyright® 1999-2002 PardesiServices, LLC

public abstract class SiteCopyright : System.Web.UI.UserControl
	protected System.Web.UI.WebControls.Label CopyRightLabel;
	protected System.Web.UI.WebControls.Panel CopyRightPanel;

	private void Page_Load(object sender, System.EventArgs e)
		if (!IsPostBack)
			CopyRightLabel.Style.Add("font-weight", "10px");
			CopyRightLabel.Style.Add("color", "#cccccc");

Load The User Controls In Web Page

The final step is to actually use your UserControl on the web page now. Following are the steps that you need to follow to include the control in the page.

  • First and mose important step is to declare @Register directive at the top of page where you want to include the UserControl. This directive has three important directives that you need to supply.
    • tagprefix - This attribute indicates the prefix that you will be using to declare your control on the page. For example, you use asp directive to declare server side controls (asp:Panel).
    • tagname - This directive indicate what name you will be using to declare this control on the web page. For example
    • src - This attribute provides the path and name of the .ascx file that contains the UserControl implementation.
    <%@ Register Tagprefix="Softomatix" Tagname="SiteFooter"
    	 Src=".\controls\SiteFooter.ascx" %>
    <%@ Register Tagprefix="Softomatix" Tagname="SiteCopyright"
    	 Src=".\controls\SiteCopyright.ascx" %>
    <%@ Page language="c#" Codebehind="Default.aspx.cs" AutoEventWireup="false"
    	 Inherits="ASPNet_App.DefaultForm" %>
  • If you are using pre-compiled DLL for the control and the assembly is not part of the current project, then you need to add the reference to the control's assembly DLL.
  • Last step is to actually include the control on the page it self.
    <div align="center">
    	<Softomatix:SiteFooter Runat="server"></Softomatix:SiteFooter>
    <div align="center">
    	<Softomatix:SiteCopyright Runat="server"></Softomatix:SiteCopyright>
Go Freelance
Home     About us     Contact us    Copyright    Privacy Policy    Return Policy    Advertisers
Copyright © Netomatix