Choose a base class for your control.
Create a namespace for your control.
Register and use your control in a page.
Extend and aggregate existing controls.
Maintain state in custom server controls.
You’ve spent the last two chapters studying ASP.NET server controls, Microsoft ADO.NET, and data-binding. By now you’re probably thinking, “These server controls sure are cool, but I wish I could create my own.” Well, wish no longer! In this chapter, you’ll learn how to create custom ASP.NET server controls.
There are nearly as many reasons for developing custom server controls as there are developers, but generally these reasons fall into three main categories: reuse, specialization, and maintenance.
Custom server controls make reuse easy. You can wrap up a bunch of related functionality and UI elements into a control, and then reuse that control where you need that functionality. For example, you could create a server control that encapsulates all of the fields and validation logic necessary for user registration. Then, instead of rewriting that code every time you need a user registration screen, you simply add your control to the page.
Specialization refers to taking an existing piece of functionality, such as a server control, and adding your own customized functionality to it. Specialization in ASP.NET server controls is typically done through inheritance. You specialize through inheritance by inheriting from a class that provides most of the functionality you want, and then adding additional functions or overriding existing ones and adding your own implementation of those functions. The TextBoxPlus control sample later in this chapter provides an example of specialization.
Finally, custom ASP.NET server controls simplify the maintenance of your applications. Once you have developed and tested a server control, you can reliably use it in many places. If you find a bug in your control, you can fix it in a single place (the source class for your control), and all you need to do to distribute the fix is replace the assembly containing the fixed control. This is a major improvement over reuse through include files (or having no reuse at all).