Adding a templated control to a Web page (C#) : TemplateContainer « Custom Controls « ASP.NET Tutorial






<%@ Page Language="C#" %>

<%@ Register Assembly="WebControlLibrary1" Namespace="WebControlLibrary1" 
    TagPrefix="cc1" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        this.TemplatedControl1.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Templated Web Controls</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <cc1:TemplatedControl Name="John Doe" Text="Hello World!" 
            ID=" TemplatedControl1" runat="server">
            <MessageTemplate>The user '<%# Container.Name %>' 
                has a message for you: <br />"<%#Container.Text%>"
            </MessageTemplate>
        </cc1:TemplatedControl>        
    </div>
    </form>
</body>
</html>

File: TemplatedControl.cs


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)