This was a real pain in the ass to figure out and searching around the internet, I couldn’t really find any straight answers. But I finally figured out how to use nested content with an ASP.NET User Control without resorting to a custom control. (Hey I’m a design-time guy.)
So let’s say you want to do this:
<uc1:Box runat="server" Title="This is cool!"> <p>This would be child content of the box control.</p> <asp:Button runat="server" Text="This works too" /> </uc1:Box>
In Box.ascx, put this:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Box.ascx.cs" Inherits="Box" %> <div id="BoxDiv" runat="server" class="box"> <h3><asp:Literal id="TitleLiteral" runat="server"/></h3> <asp:PlaceHolder id="ChildPlaceHolder" runat="server" /> </div>
In Box.ascx.cs put this:
[ParseChildren( true, "ChildControls" )]
public partial class Box : System.Web.UI.UserControl
{
public string Title
{
get
{
return TitleLiteral.Text;
}
set
{
TitleLiteral.Text = value;
}
}
/// <summary>
/// A collection of child controls nested in the user control's tags.
/// </summary>
public ControlCollection ChildControls
{
get
{
return ChildPlaceHolder.Controls;
}
}
}