asp.netcustom-server-controlsservercontrol

Server Control Create Children Elements


I want to know how do you create child elements for a server control and is there any documentation or tutorials on this e.g

<myMenu:Menu id="Menu1" runat="server">
    <myMenu:MenuItem Text="Some Text" Link="www.msdn.com"> // <--
    // ^-- Theis part how do you create child controls collection
    </myMenu:MenuItem>
</myMenu:Menu>


namespace ControlsBook2Lib.Ch08
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:Menu runat=server></{0}:Menu>")]
public class Menu : WebControl
{
    protected override void RenderChildren(HtmlTextWriter writer)
    {
        base.RenderChildren(writer);
    }
}

[ToolboxData("<{0}:MenuItem runat=server></{0}:MneuItem>")] <-- this part is wrong I know
public class MenuItem : WebControl
{
    protected override void Render(HtmlTextWriter writer)
    {
        base.Render(writer);
    }
}
}  

Solution

  • You need expose a property in parent control that holds collection of child items - note that child type need not be a control (it can be a regular class).

    See this MSDN article that describes how to develop such server control - see the example where a sample control holds collection of contact class. You also have an example of developing collection editor to provide UI for editing the same.