Custom Controls

Much of this book focuses on demonstrating how to use the cornucopia of controls provided by the .NET framework. 7 and Chapters 11 through 16 explain each control in detail, including the methods, properties, and events that make your program act the way you want.

Sometimes, however, even this incredible variety of controls is inadequate. You need a different kind of control, one not offered by the .NET Framework. In that case, you are free to create your own custom control.

In fact, there are three ways to create your own controls. Perhaps the easiest alternative is to specialize an existing control. To do so, you derive from an existing control class and then override methods or add your own properties, as you would when deriving from any existing class. Thus, you might derive from Button to make a button that counts how many times it has been clicked, or you might derive from a text box to create a phone number text box that accepts only numerals in the correct format.

A second, more powerful, alternative derives from UserControl. A UserControl is a composite control, created by combining one or more existing control types into a new control, with its own properties and methods. Thus, you might combine various text and label controls to create an address control that captures user input, or combine a button and a timer to create a button whose message changes every minute.

Do not confuse Windows Forms user controls with ASP.NET user controls. Windows Forms user controls are composite custom controls.

Finally, if you need an even more powerful alternative, you can derive from the base Control class and create a custom control from scratch. In this case, you'll be responsible for drawing your own control, but you can decide on the exact look, feel, and behavior of it. Thus, you might create a pop-up button that allows you to set its behavior, or you might create an analog alarm-clock control that displays the time as a 24-hour clock.

This chapter shows you how to create each type of custom control.

Категории