Add Controls to Control in ASP.Net (With Less Pulp)

So this should be a fairly easy showing and you’ll be on your way quickly. Hell most likely you won’t finish this sentence before going somewhere else. BUT for those who brave this post, you will be rewarded… I hope.

So here’s the problem, you have a UserControl/WebControl/ExtenderControl/ScriptControl/… (Seriously?) that you want to be able to add controls to in the markup like thus:

<SomeControl>
  <ControlList>
    <asp:Label />
    <asp:Label />
  </ControlList>
</SomeControl>

As you see here, the idea is that SomeControl actually can dynamically house controls based on the markup. Seems like this should be hard, but in reality it’s pretty simple. First start with creating a user control, which I hope you know how to do. (I’m calling it ParentControl) Second open up the class file and let’s add some stuff.

    [ParseChildren(true)]
    [PersistChildren(false)]
    public partial class ParentControl : UserControl
    {
        public ParentControl()
        {
            addedControls = new List<WebControl>();
        }

        private List<WebControl> addedControls;

        public List<WebControl> AddedControls
        {
            get
            {
                return addedControls;
            }
        }
    }

And honestly, that’s the code needed but I’ll give a literary once over to make sure things are clear.

So first off you have to add a list of controls to the eh… control and create a property that is used to access it and this can actually be done verbosely:

        //Field
        private List<WebControl> addedControls;

        //Instantiation on constructor
        public ParentControl()
        {
            addedControls = new List<WebControl>();
        }

        //Property to access
        public List<WebControl> AddedControls
        {
            get
            {
                return addedControls;
            }
        }

OR the easy way (Which is not what the original example showed:

        public List<WebControl>AddedControls { get; set; }

As you can see, the 2.0 auto property syntax will actually work for this. So if you like that, you can save yourself some typing.

Ok so now we have a property, and field if you choose, to handle this. Sounds way too easy right? Well the magic is in the attributes:

    [ParseChildren(true)]
    [PersistChildren(false)]
    public partial class ParentControl : UserControl

And you’re all set. Now the markup:

    <userControl:ParentControl ID="ParentControl1" runat="server" >
        <AddedControls>
            <asp:Label ID="labelHi" runat="server" />
        </AddedControls>
    </userControl:ParentControl>

Still waiting for this to get complicated? Well you’re going to waiting for a long time because that’s it. When page load comes around will now have a list with the label in it. Pretty nice huh?