ASP.NET User Control with Template Content user controls are great.  I use them all the time when working on .net websites.  I was working on a site using the ajax extender toolkit.  I created a panel that could be expanded collapsed with a button click.  I inserted a few into the site and liked them so much I made some more.  Well after the 7th panel it started getting tedious.  What a perfect place for a user control.  The problem was I needed to be able to place whatever custom content I wanted inside the panel.  After much searching around I wasn't finding what I wanted.  The answer it turns out is an user control with custom templates.

Create a new user control for your site.  Mine is called CollapsiblePanel.  In the code behind for the page you need to add a new class MessageContainer that inherits from Control and implements the INamingContainer Interface.   Then in the user controls OnInit method you need to check for content and add it to your user control.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test.UserControls
    // this is a message container, it contins the data we want to display
    // as well as the index of the container
    public class MessageContainer : Control, INamingContainer
        private int index;
        internal MessageContainer(int index) { this.index = index; }
        public int Index { get { return index; } }

   // this is the user control I have created
   //its an ajax extended collapsible panel with some custom content
    public partial class CollapsiblePanel : System.Web.UI.UserControl, INamingContainer
        private ITemplate _contentTemplate = null;

        public ITemplate Content
            get { return _contentTemplate; }
            set { _contentTemplate = value; }
        protected override void OnInit(EventArgs e)

            // if we have a content template in the markup then add it to our container
            if (_contentTemplate != null)
                MessageContainer container = new MessageContainer(0);

Now to use our new user control in an aspx page with some content.

<uc:CollapsiblePanel runat="server" ID="CollapsiblePanel1">
          CONTENT GOES HERE,You can drop anything, controls, etc.            


Popular posts from this blog

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC

Notify Icon Text vs BalloonTipText