Creating the template control container class (C#) : TemplateContainer « Custom Controls « ASP.NET Tutorial






using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebControlLibrary1
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:TemplatedControl runat=server></{0}: TemplatedControl >")]
    public class TemplatedControl : WebControl
    {
        private string _name;
        private string _text;

        private Message _message;
        private ITemplate _messageTemplate;

        [Browsable(false)]
        public Message Message
        {
            get
            {
                EnsureChildControls();
                return _message;
            }
        }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        [TemplateContainer(typeof(Message))]
        public virtual ITemplate MessageTemplate
        {
            get { return _messageTemplate; }
            set { _messageTemplate = value; }
        }

        [Bindable(true)]
        [DefaultValue("")]
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        [Bindable(true)]
        [DefaultValue("")]
        public string Text
        {
            get { return _text; }
            set { _text = value; }
        }

        public override void DataBind()
        {
            CreateChildControls();
            ChildControlsCreated = true;
            base.DataBind();
        }

        protected override void CreateChildControls()
        {
            this.Controls.Clear();

            _message = new Message(Name, Text);

            ITemplate template = MessageTemplate;
            template.InstantiateIn(_message);
            Controls.Add(_message);
        }

    }
}








14.14.TemplateContainer
14.14.1.Creating the template control container class (C#)
14.14.2.Creating the template control container class (VB)
14.14.3.Adding a templated control to a Web page (C#)
14.14.4.Adding a templated control to a Web page (VB)