News & UpdatesProgrammingWeb programming Store My Projects
Links
Affiliates

ASP.NET Tutorial – 10 – User Controls

Creating a User Control

A UserControl is a separate, reusable part of a page. To create one, right click on the project in the Solution Explorer and add a new item. Select the Web User Control template and give it a name. There is a check box on this dialog box that gives the option of creating a separate code page file, just as for the default page. To make things easier to overview go ahead and deselect the check box before adding the control. You have now created a user control in a single file with an .ascx extension.

Implementing a User Control

Add a label web control to the User Control.

<asp:Label ID="myLabel" 
            runat="server" 
            Text="Label" 
            ></asp:Label>

Then add an initialization event to the label and have the event handler set the label’s text to display the current day of the week.

<script runat="server">
protected void myLabel_Init(object sender, EventArgs e)
{
  myLabel.Text = DateTime.Today.DayOfWeek.ToString();
}
</script>

Including a User Control

The user control is now finished. To add it you just need to drag and drop the control to the page in design view. If you now run the application, the current day will be displayed on the label.

In markup view, you can see that two changes were made when the user control was added. First, there’s a register directive at the top to register the control for the page.

<%@ Register Src="myUC.ascx" TagName="myUC" TagPrefix="uc1" %>

Second, the control is placed on the page using a special tag constructed from the TagPrefix and TagName, which are specified in the register directive.

<uc1:myUC id="MyUC1" runat="server"></uc1:myUC>
Recommended additional reading:
Sams - Teach Yourself ASP.NET 3.5 in 24 Hours