Microsoft provided a large set of server controls as part of ASP.NET, but it couldn't possibly imagine all the different scenarios that might require reusable "chunks" of user interface or code in your applications. ASP developers used "include files" as a way of encapsulating reusable functionality, but that technique had serious limitations. (If you've never dealt with the headache of scoping issues, public variable resolution, and the other problems involved with using include files, you won't see the joy in not having to do so. But believe us, include files were a mixed blessing.)
In order to allow you to create reusable ASP.NET components, Microsoft has provided two completely separate techniques:
User controls. You can simply create a specially formatted page (with the .ascx extension) and embed it in other pages. These new controls are most like ASP's include files, but Visual Studio .NET provides a user interface for creating these components. Once you've created a user control and have added it to your project, you can simply drag and drop it onto as many pages as you want.
During the ASP.NET development process, user controls were originally called pagelets. During the process, the name was changed to user controls, but it may be beneficial to think of them as "pagelets" little pages embedded within other pages because that's really what they are.
Custom controls. You can create a class that inherits from an existing control. Custom controls are, in essence, the same thing as server controls. You would use the same techniques to create your custom controls that Microsoft used to create all the controls in the Toolbox window. This technique is beyond the scope of this book, but you'll find many resources available to help you get started creating custom controls.
COMPARING USER CONTROLS AND CUSTOM CONTROLS
Several other differences exist between user controls and custom controls. For example, custom controls can appear in the Toolbox window; user controls cannot. Custom controls provide a user interface at design time; user controls display a gray box. Custom controls' properties appear in the Properties window; user controls require you to set properties at their design time or in code once they're hosted. Custom controls are globally available and can be used in any project; user controls must be copied into the project (which means you'll end up with multiple copies of the ASCX file on your server, if you use the same user control in multiple Web projects). User controls have one capability; however, that makes them special: They can provide page caching separate from the parent page. This allows you to play some neat tricks with output caching for your pages, if you want to dig into special caching techniques for user controls.
In this chapter, you'll create some simple user controls. You'll also learn how you can reuse one or more controls, with code you've written, on as many pages as you require.