Chapter 13A. User Controls in Web Forms

ASP.NET user controls are custom, reusable controls that are both easy to create and use. User controls are a collection of controls, such as text boxes and buttons, and can include custom properties and methods that are exposed to the container of the user control. In this lesson I show you how to create and use a user control. I also show you how to expose properties on a user control.

Whenever you find that you are using the same markup in two or more places, it is time to consider copying that markup to a user control. The page shown in Figure 13A-1 collects both a mailing address and a billing address. The fields for both types of addresses, however, are identical. The address information on this form can be converted into a user control.

FIGURE 13A-1

Figure 13A.1. FIGURE 13A-1

CREATING A USER CONTROL

To create a user control, select the Web User Control template from the Add New Item dialog box (see Figure 13A-2).

FIGURE 13A-2

Figure 13A.2. FIGURE 13A-2

Warning

Because a page that uses a user control and the user control itself cannot be in the same folder, it is a best practice to create a folder especially for your user controls.

A user control has the ASCX file extension. This is the default markup that is created for a user control:

<%@ Control Language="C#" AutoEventWireup="true" ...

Get ASP.NET 4 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.