ASP.NET Custom/User Control With Children

asp.net

I want a create a custom/user control that has children.

For Example, I want my control to have the following markup:

<div runat="server" id="div">
    <label runat="server" id="label"></label>
    <div class="field">
        <!-- INSERT CHILDREN HERE -->
    </div>
</div>

and when I want to use it on a page I simply:

<ctr:MyUserControl runat="server" ID="myControl">
    <span>This is a child</span>
    <div runat="server" id="myChild">And another <b>child</b>
</ctr:MyUserControl>

The child controls inside my user control will be inserted into my user control somewhere. What is the best way to accomplish this?

The functionality is similar to a asp:PlaceHolder but I want to add a couple more options as well as additional markup and the such. Also the child controls still need to be able to be accessed by the page. (in the example above the page should have the myChild Control on it)

EDIT ——

It can be a template control as long as it allows me to reference the children on the page.

Best Answer

I asked something similar myself a while ago. See here.

I believe you will have to use an ITemplate as an InnerProperty:

[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Content
{
    get
    {
        return _content;
    }
    set
    {
        _content = value;
    }
}
private ITemplate _content;

Then override the CreateChildControls method of your control:

protected override void CreateChildControls()
{
   if (this.Content != null)
   {
      this.Controls.Clear();
      this.Content.InstantiateIn(this);
   }
   base.CreateChildControls();
}

What's the harm in using an ITemplate You can combine it with your existing markup and write whatever HTML you want within the Content property.

Related Topic