Search code examples
c#.netasp.netcustom-server-controls

ASP Nested Tags in a Custom User Control


I'm just getting started with Custom User Controls in C# and I'm wondering if there are any examples out there of how to write one which accepts nested tags?

For example, when you create an asp:repeater you can add a nested tag for itemtemplate.


Solution

  • I wrote a blog post about this some time ago. In brief, if you had a control with the following markup:

    <Abc:CustomControlUno runat="server" ID="Control1">
        <Children>
            <Abc:Control1Child IntegerProperty="1" />
        </Children>
    </Abc:CustomControlUno>
    

    You'd need the code in the control to be along the lines of:

    [ParseChildren(true)]
    [PersistChildren(true)]
    [ToolboxData("<{0}:CustomControlUno runat=server></{0}:CustomControlUno>")]
    public class CustomControlUno : WebControl, INamingContainer
    {
        private Control1ChildrenCollection _children;
    
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public Control1ChildrenCollection Children
        {
            get
            {
                if (_children == null)
                {
                    _children = new Control1ChildrenCollection();
                }
                return _children;
            }
        }
    }
    
    public class Control1ChildrenCollection : List<Control1Child>
    {
    }
    
    public class Control1Child
    {
        public int IntegerProperty { get; set; }
    }