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






<%@ Page Language="VB" %>

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

<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        Me.TemplatedControl1.DataBind()
    End Sub
</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.vb


Imports System.ComponentModel
Imports System.Web.UI
Imports System.Web.UI.WebControls

<DefaultProperty("Text")> _
<ToolboxData("<{0}:TemplatedControl runat=server></{0}:TemplatedControl>")> _
Public Class TemplatedControl
    Inherits System.Web.UI.WebControls.WebControl

    Private _name As String
    Private _text As String

    Private _message As Message
    Private _messageTemplate As ITemplate

    <Browsable(True)> Public ReadOnly Property Message() As Message
        Get
            EnsureChildControls()
            Return _message
        End Get
    End Property

    <PersistenceMode(PersistenceMode.InnerProperty), _
        TemplateContainer(GetType(Message))> _
    Public Property MessageTemplate() As ITemplate
        Get
            Return _messageTemplate
        End Get
        Set(ByVal value As ITemplate)
            _messageTemplate = value
        End Set
    End Property

    <Bindable(True), DefaultValue("")> Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

    <Bindable(True), DefaultValue("")> Public Property Text() As String
        Get
            Return _text
        End Get
        Set(ByVal value As String)
            _text = value
        End Set
    End Property

    Public Overrides Sub DataBind()
        CreateChildControls()
        ChildControlsCreated = True
        MyBase.DataBind()
    End Sub

    Protected Overrides Sub CreateChildControls()

        Me.Controls.Clear()

        _message = New Message(Name, Text)

        Dim template As ITemplate = MessageTemplate
        template.InstantiateIn(_message)
        Controls.Add(_message)
    End Sub

End Class








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)