Chapter 7
User Controls

Web forms bring component-based programming to the Internet by enabling complex rendering and behavioral logic to be encoded in reusable server control classes. Classes such as Calendar and DataGrid form the backbone of Web forms and enable developers who have only a rudimentary knowledge of HTML and client-side scripting to build sophisticated Web pages.

But the story of componentization in ASP.NET doesn鈥檛 end with server controls. ASP.NET supports a second type of component called the user control. A user control is a custom control built from HTML and server-side script. It鈥檚 an intuitive and easily understood means for capturing and sharing functionality without resorting to the server-side includes (SSIs) so prevalent in ASP programming. And it鈥檚 a mechanism for building reusable ASP.NET components that鈥檚 simpler than writing full-blown server controls. A developer familiar with the Web Forms programming model can have a basic user control up and running in no time flat. Then he or she can instantiate that control in Web forms by using declarative tags much like those used to declare DataGrids and other server controls.

User controls enjoy three primary uses:

This chapter is all about user controls鈥攚hat they are, how to write them, how to use them, and why you鈥檇 want to use them in the first place. You鈥檒l see some real working examples of user controls, including one that implements Web navigation bars, and learn how to combine user controls with HTTP cookies to create personalized content. Finally, you鈥檒l learn how user controls can improve the performance of applications built around Web forms.

User controls are one of the most important facets of the Web Forms programming model鈥攕o important, in fact, that time delayed in learning about them is time wasted. In the words of a famous American, let鈥檚 roll.