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
1 |
<%@ Control Classname=”MyTime” %> |
2 |
<table width=”40%” bgcolor=”cyan”> |
3 |
<tr> |
4 |
<td><h3>Current time is:</h3></td> |
5 |
</tr> |
6 |
<tr> |
7 |
<td><h4>
<%=Now.toString(“hh:mm:ss tt”)%> </h4></td> |
8 |
</tr> |
9 |
</table> |
- 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
1 |
<%@Register TagPrefix=”TimeControl” Tagname=”MyTime” Src=”time.ascx” %> |
2 |
<html><head></head><body> |
3 |
<TimeControl:MyTime id=”MyTime1” runat=”server” /> |
4 |
</body></html> |

- 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


Handling Events:
- Add another web user control and call it
contentRotator.ascx
- 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
