Thursday, 4 March 2010

Asp.Net: Create Simple Template Control

Question:
How to build a very simple Template Control in asp.net?
Do you have a sample for simplest Template Control.
Create your own Template Controls!



Answer:
A template control is a control that will render one or more of the templates depending on certain conditions.
The simplest template control has one template that always shows.

Here is a "Hello World" example

Page code
<%@ Register tagprefix="ctrl" Namespace="TemplateTest" Assembly="TemplateTest" %>
...
<ctrl:HelloWorldTemplateControl  runat="server">
    <HelloTemplate>
        Hello World
    </HelloTemplate>
</ctrl:HelloWorldTemplateControl>


Control code
[ParseChildren(true)]
[PersistChildren(false)]
public class HelloWorldTemplateControl : Control, INamingContainer
{
    private ITemplate _helloTemplate;
     
    [PersistenceMode(PersistenceMode.InnerProperty),
    TemplateContainer(typeof(HelloWorldTemplateControl))]
    public ITemplate HelloTemplate
    {
        get { return _helloTemplate; }
        set { _helloTemplate= value; }
    }

    protected override void CreateChildControls()
    {
        Controls.Clear();
        if (HelloTemplate != null)
        {
            HelloTemplate.InstantiateIn(this);
        }
    }
}

No comments: