Building Composite Controls
When you build composite controls, the
Render method takes on a different form. Since the control tree is already built once you enter the
Render method, all you can do is provide the surrounding formatting, and apply formatting to the controls already in the tree. You still need to use the child control's rendering capabilities to render the control. Not doing so makes the child control invisible to the user and probably useless within the control. For the formatting surrounding the controls you can use the same methods as beforeyou can format the child controls either explicitly or by setting properties on the controls, or by applying a style. To apply a style, you again need a Styleobject. You can use the
ControlStyle if you just want to propagate the main style to the child controls, or one defined in a public Style property.
Listing 6 shows the body code for a composite control that shows a
TextBox with a caption. The Caption takes the formatting of the control itself, but you can format the
TextBox through a separate style. Notice that I defined the
TextBox globally because multiple methods need to access itfirst when the code adds the control to the control tree, and later to apply the style and render the control. You could also apply the style in the
CreateChildControls method, but that would cause the style of the child control to be stored in the ViewState, in addition to the Style object that has been applied. This would result in a larger
ViewState for no reason whatsoever. The
ApplyStyle method copies all properties from the originating style to the
ControlStyle of the child control, overriding any existing style properties already set on the child control. If you only want to override blank properties, you should use the
MergeStyle method instead.
You can apply formatting to controls in several ways. The best way differs per control, but in most cases you will want to keep the outer tags of the control as defined by the parent control. This means you should override the
RenderContents method instead of the
Render method. When you work with composite controls, keep in mind that you can tweak the formatting of the child controls during the Render phase. In addition, you can add additional HTML during this phase so you can actually create a sparse control tree surrounded by HTML generated in the
Render or
RenderContents method. This is more efficient than adding more controls to the control tree.