C# – Create custom panel control

asp.netcpaneluser-controls

A Server based control is not good solution for me, since my panel should by default always contain a asp checkbox which will allow the user to hide and show the panels content.

I created my Panel as a templated user control but now I have the problem that I cannot declare variables in it.

[ParseChildren(true)]
public partial class MyPanel: System.Web.UI.UserControl
{

    private ITemplate messageTemplate = null;

    [TemplateContainer(typeof(MessageContainer))]
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public ITemplate Content
    {
        get
        {
            return messageTemplate;
        }
        set
        {
            messageTemplate = value;
        }
    }

    void Page_Init()
    {
        MessageContainer container = new MessageContainer();
        messageTemplate.InstantiateIn(container);
        PlaceHolder1.Controls.Add(container);
    }

    [ParseChildren(true)]
    public class MessageContainer : Control, INamingContainer
    {

        internal MessageContainer()
        {
        }

    }
}

If I do the following in MyPage.aspx then the control definitions are not inserted into MyPage.aspx.designer.cs a they do normally:

<my:MyPanel>
  <Content>
    <asp:TextBox id = "foo" runat="server" />
  </Content>
</my:MyPanel>

Therefore foo is not created as control variable by the designer, so I have no access to it.

How can I create my own Panel which allows declaration of controls in it?

EDIT:
I now tried with [ParseChildren(false)]. Variables for contained variables are now generated in the designer code of the form. The problem is now that messageTemplate.InstantiateIn(container) throws an exception.

Best Answer

You haven't given code for the control. In general, it needs to implement INamingContainer and should have properties of type ITemplate to accept templates. Check on MSDN on how to develop one. And here's the sample code from MSDN. Also check this article for data bound templated control.