8.1. Introduction to User Controls

User controls are great for encapsulating markup, controls, and code that you need repeatedly throughout your site. While master pages allow you to create content that is displayed in all pages in your site, it's common to have content that should only appear on some but not all pages. For example, you may want to display a banner on a few popular pages, but not on the home page or other common pages. Without user controls, you would add the code for the banner (an image, a link, and so on) to each page that needs it. When you want to update the banner (if you want to use a new image), you need to make changes to all pages that use it. If you move the banner to a user control and use that control in your content pages instead, all you need to change is the user control, and the pages that use it pick up the change automatically. This gives you a flexible way to create reusable content.

User controls have the following similarities with normal ASPX pages:

  • They have a markup section where you can enter standard markup and server controls.

  • They can be created and designed with Visual Web Developer in Markup and Design View.

  • They can contain programming logic, either inline or with a Code Behind file.

  • You have access to page-based information like Request.QueryString.

  • They raise some (but not all) of the events that the Page class raises, including Init, Load, and PreRender.

You should also be aware of a few differences. User controls have an .ascx extension ...

Get Beginning ASP.NET 3.5: In C# and VB now with O’Reilly online learning.

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