User Controls

User controls allow you to save a part of an existing ASP.NET page and reuse it in many other ASP.NET pages. A user control is almost identical to a normal .aspx page, with the following differences:

  • User controls have an .ascx extension rather than an .aspx extension.

  • User controls may not have <html>, <body>, or <form> tags.

  • User controls have a Control directive rather than a Page directive.

The simplest user control is one that displays only HTML. A classic example of a simple user control is an HTML page that displays a copyright notice.


User controls were originally called pagelets, which we think is more descriptive; alas, Microsoft has elected to call them user controls and so shall we. When you see the term user control, think this: a bit of a content page that can be reused in other content pages.

Visual Studio 2008 (VS2008) provides support for creating user controls. To see this at work, create a new website named C15_UserControls. Right-click the website folder in the Solution Explorer and choose Add New Item to bring up the Add New Item dialog box. Select Web User Control and give it the name Copyright.ascx.

This choice opens the new file in Source view. Initially, the file contains only a Control directive:

<%@ Control Language="C#" AutoEventWireup="true"
    CodeFile="Copyright.ascx.cs" Inherits="Copyright" %>

This directive, similar to the Page directive described in Chapter 6, sets the language, the name of the code-behind file, the class, and so on.

Copy the ...

Get Programming ASP.NET 3.5, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.