Question

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?

Was it helpful?

Solution

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);
}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top