What is the easiest way to set the contents of an <asp:ContentPlaceHolder>
programatically? I imagine ill have to do a Master.FindControl
call?
views:
1582answers:
3
A:
If you are adding controls to a blank page then you do Page.Controls.Add()....no?
dev.e.loper
2008-11-14 19:06:41
sorry i omitted that i want the contents filled, not actual controls generated
Anders
2008-11-14 19:11:58
Filled with anything specific? Raw html or text?
dev.e.loper
2008-11-14 20:46:32
text only, I have the formatting HTML outside the contentplaceholder
Anders
2008-11-14 22:01:26
+2
A:
If your page inherits from a MasterPage, then you should have an asp:Content control on your page with some id, like so:
<asp:Content runat="server" ID="myContent" ContentPlaceHolderID="masterContent">
</asp:Content>
You should be able to reference this in your codebehind and add whatever you want to it.
public void Page_Load( object sender, EventArgs e )
{
HtmlContainerControl div = new HtmlContainerControl( "DIV" );
div.innerHTML = "....whatever...";
myContent.Controls.Clear();
myContent.Controls.Add(div);
}
[EDIT] Please excuse my C# syntax and translate as needed. I didn't see the VB.NET tag until after saving my response.
tvanfosson
2008-11-15 04:08:48
A:
I use a custom extension method that searches a control (a placeholder for example) recursively to find the control you're looking for by Id and return it. You can then populate the returned control as required. Call this in a foreach loop iterating over your list of controls to populate.
public static class ControlExtensions
{
/// <summary>
/// recursive control search (extension method)
/// </summary>
public static Control FindControl(this Control control, string Id, ref Control found)
{
if (control.ID == Id)
{
found = control;
}
else
{
if (control.FindControl(Id) != null)
{
found = control.FindControl(Id);
return found;
}
else
{
foreach (Control c in control.Controls)
{
if (found == null)
c.FindControl(Id, ref found);
else
break;
}
}
}
return found;
}
}
flesh
2008-11-15 09:07:02