Designing Custom Controls
ASP.NET provides the ability to define two kinds of custom controls: user controls and server controls. The purpose of both is the same: to encapsulate visual and programmatic behaviors for use on web pages. (For example, a control can be used to encapsulate a navigation bar that appears on every page in a site.) Their differences lie in how they are created and in their capabilities. User controls are created in much the same way as standard ASP.NET pages and can include HTML, embedded code, and code-behind files. This allows web developers to quickly and easily create controls using techniques with which they are already familiar. In contrast, server controls are created entirely in code and provide much more sophisticated control over rendering, postback processing, and event generation. This means that custom server controls can do everything that built-in ASP.NET server controls can do. Even so, user controls are usually the right choice because they are so simply created. Server controls are not needed unless user controls are not sufficient for a given purpose. This section shows how to create both kinds of controls.
The easiest way to create a new control
is to aggregate and modify the functionality of one or more existing
controls. This is done by creating a user-control file
) and then referencing it from a web page
.aspx). Example 6-17 shows
a simple user-control file.
Example 6-17. A user control for implementing ...