Render multiple control collections in ASP.NET custom control

Posted by Monty on Stack Overflow See other posts from Stack Overflow or by Monty
Published on 2010-03-15T13:38:23Z Indexed on 2010/03/15 13:39 UTC
Read the original article Hit count: 307

I've build a custom WebControl, which has the following structure:

<gws:ModalBox ID="ModalBox1" HeaderText="Title" runat="server">
    <Contents>(controls...)</Contents>
    <Footer>(controls...)</Footer>
</gws:ModalBox>

The control contains two ControlCollection properties, 'Contents' and 'Footer'. Never tried to build a control with multiple control collections, but solved it like this (simplified):

[PersistChildren(false), ParseChildren(true)]
public class ModalBox : WebControl
{
    private ControlCollection _contents;
    private ControlCollection _footer;

    public ModalBox()
        : base()
    {
        this._contents = base.CreateControlCollection();
        this._footer = base.CreateControlCollection();
    }

    [PersistenceMode(PersistenceMode.InnerProperty)]
    public ControlCollection Contents { get { return this._contents; } }

    [PersistenceMode(PersistenceMode.InnerProperty)]
    public ControlCollection Footer { get { return this._footer; } }

    protected override void RenderContents(HtmlTextWriter output)
    {
        // Render content controls.
        foreach (Control control in this.Contents)
        {
            control.RenderControl(output);
        }

        // Render footer controls.
        foreach (Control control in this.Footer)
        {
            control.RenderControl(output);
        }
    }
}

However it seems to render properly, it doesn't work anymore if I add some asp.net labels and input controls inside the property. I'll get the HttpException:

Unable to find control with id 'KeywordTextBox' that is associated with the Label 'KeywordLabel'.

Somewhat understandable, because the label appears before the textbox in the controlcollection. However, with default asp.net controls it does work, so why doesn't this work? What am I doing wrong? Is it even possible to have two control collections in one control? Should I render it differently?

Thanks for replies.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET