Chapter 8
Custom Controls

As you learned in Chapter 6, the .NET Framework class library (FCL) features a rich collection of server controls that provide ready-made building blocks for Web forms. FCL control types range from the simple (Label) to the sublime (Calendar, DataGrid, Repeater, and others), and they enable developers to build sophisticated Web applications without getting lost in a maze of HTML and client-side scripting.

Diverse as they are, the FCL鈥檚 built-in server controls can鈥檛 possibly accommodate the needs of every developer. The time will come when you need a control that鈥檚 not part of the FCL. Then you鈥檒l have two choices: purchase the control from a third party or write it yourself. This chapter is about the latter: how to write custom controls that look and feel like FCL controls but encapsulate functionality that FCL controls don鈥檛. Among other things, you鈥檒l learn how controls render themselves to Web pages, how controls process postback data and generate postbacks of their own, how controls use view state to persist data across requests, how to write controls that do some of their processing on the client side by emitting JavaScript, and how to build controls that escape the bonds of HTML by deriving their appearance from dynamically generated images. You鈥檒l see many working examples, including one that paints a realistic-looking odometer onto a Web page and another that creates numbers-only text input fields.

ASP.NET鈥檚 server control architecture is such that writing a simple control is relatively easy and writing a complex control is鈥攚ell鈥攃omplex. Still, the ability to write custom controls is an essential skill that every ASP.NET developer should possess. Even if you never intend to write a custom control, you鈥檒l find the knowledge in this chapter edifying because it speaks volumes about how ASP.NET works.