Skip Navigation LinksASP.Net 2.0 Training : ASP.Net User Controls
Banner for ASP.Net 2.0 training classes in Visual Basic 2005 

Skip Navigation Links
Visit my other site:

certification training

Free Flash tutorials and training

Free Dreamweaver Video Tutorials

Free PHP Training

Visual Basic Windows Training

If you like this site please link to it

User Controls

A user control allows you to package frequently used user interfaces and the processing logic in a way that can be used as a pluggable component

Use Web User Controls to create reusable page elements

  • Headers
  • Footers
  • Navigation bars
  • Menus

You can also use them to create new controls out of other multiple controls

Code Example:


<%@ Control Classname=”MyTime” %>


<table width=”40%” bgcolor=”cyan”>




<td><h3>Current time is:</h3></td>







<%=Now.toString(“hh:mm:ss tt”)%> </h4></td>





Save as: Time.ascx

  • This code gets the current time from the server
  • The user control is saved with a .ascx extension
  • The server doesn’t allow you to load the .ascx file directly in your browser. A user control can only be requested from within a web form


<%@Register TagPrefix=”TimeControl” Tagname=”MyTime” Src=”time.ascx” %>




<TimeControl:MyTime id=”MyTime1” runat=”server” />



Save as: GetTime.aspx

  • TagPrefix
    • Namespace the user control belongs to
  • Tagname
    • Name the user control is recognized by
  • Src
    • Virtual path to the source code file of the user control


  • User Controls can be composed of HTML controls, ASP.Net server controls, client-side scripts and other user controls\
  • User controls always end in .ASCX
  • User Controls cannot be requested from the server directly
  • If the web form that you are converting to a user control has a @page directive then change it to a @Control directive

Open Visual Studio

  • Add a new item to your website, select User Control

  • Name it Header.ascx and click Open

  • Type Your Company Name at the top and center it
  • Add a horizontal Rule from the HTML tab of the toolbox

  • Adjust the properties as you like and save it

  • Add a new web form page and call it Main.aspx
  • Drag the Header.ascx from the solution explorer to the page

  • Test it

Handling Events:


  • Add another web user control and call it


  • Add a label control, call it lblDisplay, erase the text property
  • Double-Click the page and add the following code to the

page_load event
   Select Case Int(Rnd()*3)
   Case 0
      lblDisplay.text=”content 1”
   Case 1
      lblDisplay.text=”content 2”
   Case 2
      lblDisplay.text=”content 3”
   End Select

  • The page_load in a web user control loads differently
  • First the page_load in the containing page executes and then the user control’s page_load executes
  • Drag the contentRotator.ascx to your aspx page
  • Test it
  • Right-click and refresh browser a few times

      ASP.Net 2.0 tutorials & training