Template control not displaying Container properties


F

fusionmaster

I am trying to create a templated control for asp.net 2.0 using the example
found in the documentation, however when outputing <%# Container.Message %>
it always returns an empty string. Please help.


control code:

using System;
using System.Web;
using System.Web.UI;

namespace TemplateControlSamples
{

public class TemplateItem : Control, INamingContainer
{
private String _message = null;

public TemplateItem(String message)
{
_message = message;
}

public String Message
{

get
{
return _message;
}
set
{
_message = value;
}
}
}

[
ParseChildren(true)
]
public class Template1 : Control, INamingContainer
{

private ITemplate _messageTemplate = null;
private String _message = null;

public String Message
{

get
{
return _message;
}
set
{
_message = value;
}
}

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

protected override void CreateChildControls()
{

// If a template has been specified, use it to create children.
// Otherwise, create a single literalcontrol with message value

if (_messageTemplate != null)
{
Controls.Clear();
TemplateItem i = new TemplateItem("this is a test");
_messageTemplate.InstantiateIn(i);
Controls.Add(i);
}
else
{
this.Controls.Add(new LiteralControl(this.Message));
}
}
}
}


asp code:

<%@ Register TagPrefix="test" Namespace="TemplateControlSamples" %>
<test:Template1 ID="Template1_1" Message="Hello World!" runat=server>
<MessageTemplate>
[<%# Container.Message %>]
</MessageTemplate>
</test:Template1>


the output to the browser is always []
it sould be [Hello World!]
 
Ad

Advertisements

F

Fredrik Örvill

You must do databind to get your databinding statements (<%# %>) to get
their values. After you add your Templated item to the page, do a
i.DataBind(). Like this:

if (_messageTemplate != null)
{
Controls.Clear();
TemplateItem i = new TemplateItem("this is a test");
_messageTemplate.InstantiateIn(i);
Controls.Add(i);
i.DataBind();
}
else
{
this.Controls.Add(new LiteralControl(this.Message));
}

regards
/Örvill
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top