Set ASP:ContentPlaceHolder Content programmatically
Asked Answered
B

3

1

What is the easiest way to set the contents of an <asp:ContentPlaceHolder> programmatically? I imagine ill have to do a Master.FindControl call?

Bobby answered 14/11, 2008 at 19:2 Comment(0)
S
4

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 HtmlGenericControl( "DIV" );
    div.innerHTML = "....whatever...";
    myContent.Controls.Clear();
    myContent.Controls.Add(div);
}
Salot answered 15/11, 2008 at 4:8 Comment(2)
I know this is old, but technically it should be new HtmlGenericControl("div"), HtmlContainerControl is abstract and can't be created (although you can cast the "div" variable to that type).Tautologism
@Tautologism - thanks...and I am so glad I've left webforms behind.Salot
E
0

If you are adding controls to a blank page then you do Page.Controls.Add()....no?

Execration answered 14/11, 2008 at 19:6 Comment(3)
sorry i omitted that i want the contents filled, not actual controls generatedBobby
Filled with anything specific? Raw html or text?Execration
text only, I have the formatting HTML outside the contentplaceholderBobby
L
0

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;
    }
}
Lallation answered 15/11, 2008 at 9:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.