3

I have a custom web part that I am trying to call the RenderContents method on, but the results only contains the surrounding div for the web part, and not any child controls.

Take for example this simple web part:

namespace MyWebParts
{
  public class MyTestWebPart : WebPart
  {
    public MyTestWebPart()
    {
      this.CssClass = "myTestWebPart";
    }
    protected override void CreateChildControls()
    {
      base.CreateChildControls();

      this.Controls.Add(new LiteralControl("Nothing here yet."));
    }
  }
}

Then, in an http handler, I'm trying to instantiate this web part and call its RenderControl method. The result is <div class="myTestWebPart"></div>.

Does anyone know why I am not getting my controls from CreateChildControls also added to the output?

TehOne
  • 2,569
  • 3
  • 26
  • 36

2 Answers2

2

It's because when you're only instantiating a control and calling RenderControl on it, without it being added to a Controls collection, then it's not part of the Page lifecycle which causes all the events to fire.

In particular the PreRendering which calls EnsureChildControl isn't called.

The easy solution is to override Render like this:

protected override void Render(HtmlTextWriter writer)
{
  EnsureChildControls();
  base.Render(writer);
}
Per Jakobsen
  • 3,767
  • 17
  • 19
  • I take it this means my page lifecycle events won't be fired correctly either then? I have an overridden OnInit method in my web part as well. So I guess this won't be fired either. Also, just for full disclosure, I'm not directly instantiating my web part. I'm actually getting an instance of it using SPLimitedWebPartManager (not sure if that makes a difference). – TehOne Mar 24 '11 at 18:22
0

i would suggest to write your code in render method rather than writing in createchild control