Templated Controls FindControl() error

D

David Rees

Before I was using LoadControl and a slew of User Controls to achive the
same effect, but I realised a custom TemplatedControl was the better way of
doing it.

Anyway, this is the templated control's markup:

<ams:Comments id="amsComments" runat="server">
<Header>
<div id="CommmentList">
<h3 class="box">Article Comments</h3>
</Header>
<CommentTemplate>
<div class="Comment box">
<p class="ByLine"><ams:Author id="amsCommentAuthor" runat="server" />
posted this on <asp:Literal ID="amsCommentDate" Runat="server" /></p>
<asp:Literal ID="amsCommentContent" Runat="server" />
</div>
</CommentTemplate>
<Message>
<div class="box">
<p><asp:Literal id="amsMessage" runat="server" /></p>
</div>
</Message>
<Footer>
</div>
</Footer>
</ams:Comments>

I get the CommentTemplate ITemplate to .Instatiate() in a newly created
PlaceHolder then use that PlaceHolder's .FindControl() method to locate the
"amsCommentAuthor" and "amsCommentDate" controls and set their properties.

....but when there are more than two comments to render I get this Exception
once the first has been rendered:

Multiple controls with the same ID 'amsCommentAuthor' were found.
FindControl requires that controls have unique IDs.

but this doesn't seem right, since I was calling it from the PlaceHolder, so
it must have its own unique control ID namespace, even after explicitly
setting the PlaceHolder's .ID property.

Here's the C# causing the problem:


for(int i=0; i<cnt; i++) {

PlaceHolder phComment = new PlaceHolder();
phComment.ID = "comment_" + i.ToString();

_comment.InstantiateIn( phComment );

this.Controls.Add( phComment );

Author amsCommentAuthor = (Author)phComment.FindControl(
"amsCommentAuthor" );

amsCommentAuthor.amsAuthorHref = UrlHandler.GenerateLink(
"/AMS:ContactUser", _comments.User.Username );
amsCommentAuthor.amsAuthorName = _comments.User.Username;

Literal amsDatePosted = (Literal)phComment.FindControl("amsCommentDate");
amsDatePosted.Text = _comments.DateCreated.ToString();

Literal amsContent = (Literal)phComment.FindControl("amsCommentContent");
amsContent.Text = _comments.Content;

}

Any ideas?

Many thanks
 

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

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top