When creating custom ASP.NET controls, there's the question of which baseclass to use for your control.
Generally speaking, you have three big categories:
- Rendered Controls
- Container Controls
- Inherited Controls
Of those choices, inherited controls are the simplest, in that they simply inherit from an existing control (custom or otherwise). An example would be inheriting from a DropDownList and adding some custom code to pre-populate it. Or a ConfirmButton control, which inherits from Button, and automatically renders a "are you sure?" javascript alert when you click it. Inherited Controls are to be used when you want all the functionality of a certain control, and then just "something" extra.
Rendered Controls are created by inheriting from the WebControl class. They operate by directly injecting HTML into the output stream. As such they bypass the normal event lifecycle for any of its containing subcontrols. The result is that a Rendered Control will render much faster than a Container Control, but does not support event postbacks 'out-of-the-box'. While it is possible to provide these events, by means of implementing IPostBackEventHandler and IPostBackDataHandler, and then providing custom code to handle these events, this does raise complexity a bit and tends to create quite cluttered code. It is advisable then, to only use Rendered Controls, for simple, mostly static controls.
Container Controls, as their name implies, function as containers or collections for other controls. They are implemented by inheriting from CompositeControl. Your subcontrols are dynamically added to the Control collection of your CompositeControl, and they will then go through their normal event lifecycle, allowing you to customise them as needed. While this functionality comes at a price (somewhat worse performance compared to Rendered Controls), it allows you to build your webcontrols in a true object-oriented fashion, and apply all your usual Design Patterns to them. It also makes it much easier to inherit from your own controls, and in doing so, create an reusable and extensible library of server controls.
The choice between those three types of controls is - as is usually the case - dependant on the requirements of your project, but generally speaking, Composite Controls will be your best friend the moment your controls become a bit more complex and require event interaction.
1 comment:
Thx for the help Sam!
Post a Comment