문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top