For the reasons cited earlier in the chapter, user controls are
not always the ideal choice for reuse. They tend to be very good for quickly
reusing existing user interface elements and code, but are not especially
useful for developing reusable building blocks for multiple web applications.
This is where custom server controls come in.
A custom server control is, in its essence, a class that derives
from either the Control or WebControl class of the
System.Web.UI namespace, or from one of the classes that derive from these
controls. Custom server controls can be used in your ASP.NET Web Forms pages
in very much the same way you use the built-in server controls that come with
ASP.NET. There are two primary categories of custom server controls:
Rendered controls
Rendered controls consist largely of custom rendering
of the text, tags, and any other output you desire, which may be combined
with the rendered output of any base class your control is derived from.
Rendered controls override the Render method of the control they derive
from. This method is called automatically by the page containing the control
when it's time for the control output to be displayed.
Compositional controls
Compositional controls get their name from the fact
that they are composed of existing controls whose rendered output forms the
UI of the custom control. Compositional controls create their constituent
controls by overriding the CreateChildControls method of the control they
derive from. This method, like the Render method, is automatically called by
ASP.NET at the appropriate time.
When designing a new custom server control, you need to consider
some issues to decide which type of control to create:
Does one existing control provide most, but not all, of
the functionality you desire? Then a rendered control that derives from that
control may be the right choice.
Could the desired functionality be provided by a group
of existing controls? Then a compositional control may be a great way to
reuse those controls as a group.
Do you want to do something that is completely beyond
any existing control? Then you may want to derive your control from the
Control class and override the Render method to
create your custom output.
Note that by default, custom server controls expose all public
members of the class from which they are derived. This exposure is important
to consider when designing a control for use by other developers if you want
to limit the customizations they can make. For instance, you might not want
developers to change the font size of your control. In such a case, you should
avoid deriving from a control that exposes that property.