locked
Get Rendered HTML from User Control RRS feed

  • Question

  • User800858375 posted

    Hi everyone,

    It is possible to grab the HTML output from a custom control by doing the following:

    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    HtmlTextWriter htmlTw = new HtmlTextWriter(sw);
    
    myCustomControl.RenderControl(htmlTw);
    
    string controlsHTML = sb.ToString(); 

    I was wondering how you could do the same of a User control and its entire contents. Take an example that a user control contains some standard HTML markup as well as a GridView control and a Button control. The GridView would normally be data bound in the Page_Load event.

    If you use LoadControl("target.ascx") and grab the rendered contents:

    A > Only the standard HTML markup is retrieved
    B > The GridView does not get data bound

    How can you bind the grid view, and then retrieve the entire contents of the user control?

     Thanks again,
    Ad 

    Sunday, July 15, 2007 11:48 AM

Answers

  • User800858375 posted

    Hi again,

    I answered my own question. the solution is actually pretty obvious. You have to simply override the Rendercontrol method within the user control:

    public override void RenderControl(HtmlTextWriter writer)
    {
        GridView.DataSource = myDataSource;
        GridView.DataBind();
    
        base.RenderControl(writer);
    }

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 15, 2007 12:33 PM

All replies

  • User800858375 posted

    Hi again,

    I answered my own question. the solution is actually pretty obvious. You have to simply override the Rendercontrol method within the user control:

    public override void RenderControl(HtmlTextWriter writer)
    {
        GridView.DataSource = myDataSource;
        GridView.DataBind();
    
        base.RenderControl(writer);
    }

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 15, 2007 12:33 PM
  • User1508857181 posted

    When I try with following code in load event of page

    ======== 

    Dim uc As Control = Page.LoadControl("dg.ascx")
    PlaceHolder1.Controls.Add(uc)
    Dim sb As New StringBuilder
    Dim sw As New IO.StringWriter(sb)
    Dim hw As New HtmlTextWriter(sw)

    uc.RenderControl(hw)

    Dim controlsHTML As String = sb.ToString()

     ==========

    I get error : Control 'ctl02_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

    where GridView1 is a gridview control placed in dg.ascx.

    Any ideas?

    -Pinal Bhatt

    Tuesday, March 18, 2008 4:49 PM