Thursday, October 30, 2014

Custom Server Controls That Wrap Content

So when building a custom server control, most Google results will tell you to use a Template Control to handle wrapping your control around content. This results in markup that looks like this:

<uc:MyControl runat="server">
    <Content>
        <asp:TextBox runat="server"/>
    </Content>
</uc:MyControl>

This is annoying, since you have to specifically add a <content> section every time you'd use the wrapping control.

The solution is actually rather simple:

public override void RenderControl(HtmlTextWriter writer)
{
    // top of your wrapping code here

    foreach (Control i in Controls)
        i.RenderControl(writer);

    // bottom of your wrapping code here
}

This lets you wrap whatever code you need around whatever controls are nested inside your markup start/end tags.

No comments:

Post a Comment