views:

52

answers:

1

Hi,

I'm trying to create a really simple templated control. I've never done it before, but I know a lot of my controls I have created in the past would have greatly benefited if I included templating ability - so I'm learning now.

The problem I have is that my template is outputted on the page but my property value is not. So all I get is the static text which I include in my template.

I must be doing something correctly because the control doesn't cause any errors, so it knows my public property exists. (e.g. if I try to use Container.ThisDoesntExist it throws an exception).

I'd appreciate some help on this. I may be just being a complete muppet and missing something. Online tutorials on simple templated server controls seem few and far between, so if you know of one I'd like to know about it.

A cut down version of my code is below.

Many Thanks, James

Here is my code for the control:

[ParseChildren(true)]
public class TemplatedControl : Control, INamingContainer
{
    private TemplatedControlContainer theContainer;

    [TemplateContainer(typeof(TemplatedControlContainer)), PersistenceMode(PersistenceMode.InnerProperty)]
    public ITemplate ItemTemplate { get; set; }

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

        theContainer = new TemplatedControlContainer("Hello World");

        this.ItemTemplate.InstantiateIn(theContainer);

        Controls.Add(theContainer);
    }
}

Here is my code for the container:

[ToolboxItem(false)] 
public class TemplatedControlContainer : Control, INamingContainer
{
    private string myString;

    public string MyString
    {
        get
        {
            return myString;
        }
    }

    internal TemplatedControlContainer(string mystr)
    {
        this.myString = mystr;
    }
}

Here is my mark up:

<my:TemplatedControl runat="server">
    <ItemTemplate>
        <div style="background-color: Black; color: White;">
            Text Here: <%# Container.MyString %>
        </div> 
    </ItemTemplate>
</my:TemplatedControl>
+1  A: 

you should invoke method DataBind on your control.

one possibility is to add DataBind call in CreateChildControls()method:

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

    theContainer = new TemplatedControlContainer("Hello World");

    this.ItemTemplate.InstantiateIn(theContainer);

    Controls.Add(theContainer);

    this.DataBind();

}
stefano m
You are a saviour. Excellent. Thanks a lot - I knew it was going to be simple! The learning continues...Cheers,James
No Average Geek