By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,041 Members | 1,793 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,041 IT Pros & Developers. It's quick & easy.

Insert child controls into User Controls

P: n/a
Hi all!

Following is the method I use to insert child controls into user
controls, so that you may use them just like ordinary custom controls:


public class MyUserControl: UserControl
protected PlaceHolder ChildrenHolder = null;
protected PlaceHolder EndMarker = null;

protected override void RenderChildren(HtmlTextWriter writer)
if (this.ChildrenHolder !=null && this.EndMarker != null)
int cIndex = this.ChildrenHolder.Controls.Count;
int eIndex = this.Controls.IndexOf(this.EndMarker);
int maxIndex = this.Controls.Count - 1;

for (int i = maxIndex; i > eIndex; i --)
Control c = this.Controls[i];
this.ChildrenHolder.Controls.AddAt(cIndex, c);



Then in user controls you use: (TextBlock.ascx)

<%@ Control ...... %>
<div class='TextBlock-Content'>
<%-- Children controls will be inserted here --%>
<asp:PlaceHolder runat='server' ID='ChildrenHolder'/>
<%-- Mark the end of this user control --%>
<asp:PlaceHolder runat='server' ID='EndMarker'/>


Now in SomePage.aspx:

<my:TextBlock runat='server'>
Hello World!


Now the output will be:

Begin! Hello World! End!
Without this, child controls added into user controls will be appended
at the end. And that would output:
Begin! End! Hello World!
Please give me comment!

Nov 19 '05 #1
Share this Question
Share on Google+
1 Reply

P: n/a
Aquila Deus wrote:

Colored and formatted code:

Nov 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.