0

I am writing an ASP.NET custom control.

In my custom control code, I find a PlaceHolder control in the page like so:

this.myPlaceholder = Page.FindControl("placeholder1") as PlaceHolder;

Then, I render the placeholder as the output of the custom control:

protected override void Render(HtmlTextWriter output)
{
    if (this.myPlaceholder != null)
    {
        this.myPlaceholder.RenderControl(output);
    }
}

However, this causes the placeholder to be rendered in two places - in the custom control output (good) and in the original location in the page (bad).

Is there any way I can remove this placeholder from the page so it is only output inside the custom control?

frankadelic
  • 20,543
  • 37
  • 111
  • 164

1 Answers1

3

The Page object (and all web controls) has a collection of controls... called, conveniently enough, Controls. So Page.Controls.Remove(myPlaceholder) should do the trick.

Although... ASP.NET might complain about a control modifying its parent. In that case, you probably need to call a method on your parent page to do the dirty work, or fire off an event that your parent handles.

Bryan
  • 8,748
  • 7
  • 41
  • 62
  • +1 You beat me on that one by seconds. Removing my answer, since your is better – PHeiberg Feb 26 '10 at 20:34
  • I called Page.Controls.Remove(this.myPlaceholder) from within the Render method above. I get the error "Collection was modified; enumeration operation may not execute". – frankadelic Feb 26 '10 at 20:39
  • 1
    Right... order of operations is important here. You have to remove this form your page before the Render event starts. Do it in PreRender. – Bryan Feb 26 '10 at 20:50