91
<form runat="server" id="f1">
    <div runat="server" id="d">
        grid view:
        <asp:GridView runat="server" ID="g">
        </asp:GridView>
    </div>

    <asp:TextBox runat="server" ID="t" TextMode="MultiLine" Rows="20" Columns="50"></asp:TextBox>
</form>

Code behind:

public partial class ScriptTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        g.DataSource = new string[] { "a", "b", "c" };
        g.DataBind();

        TextWriter tw = new StringWriter();
        HtmlTextWriter h = new HtmlTextWriter(tw);    
        d.RenderControl(h);
        t.Text = tw.ToString();
    }
}

Even the GridView is within a from tag with runat="server", still I am getting this error.

Any clues please ?

4
  • 2
    I've seen this before if someone is using a Master page that already has a form tag (that may or may not already be declaring runat="server" in it's <form> tag). Just a thought...
    – lhan
    Jun 14, 2011 at 12:53
  • @Lloyd: But I don't have any Master Page, I have created this page for testing this error only.
    – teenup
    Jun 14, 2011 at 12:58
  • Hi, I copied your code but cannot replicate the problem. Can you please put the whole file contents (every line) into your question, or Pastebin it? Thanks
    – christofr
    Jun 14, 2011 at 13:01
  • 1
    possible duplicate of GridView must be added to a form tag for rendering. Jun 14, 2011 at 13:17

6 Answers 6

186

You are calling GridView.RenderControl(htmlTextWriter), hence the page raises an exception that a Server-Control was rendered outside of a Form.

You could avoid this execption by overriding VerifyRenderingInServerForm

public override void VerifyRenderingInServerForm(Control control)
{
  /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
     server control at run time. */
}

See here and here.

4
  • I have a GridView whose contents I want to render into an Email Message, thats why I need to render it out of form. I can not override this method because the host page is of Sharepoint. My Grid is a Usercontrol inside a web part in sharepoint page.
    – teenup
    Jun 14, 2011 at 13:04
  • Also, when I add that GridView directly to an HtmlForm dynamically, and then render it, it perfectly renders. This means that it only requires the presence of a form outside grid. But, when I add that DIV to the HtmlForm dynamically, this error again comes, although the Grid is a child of DIV and also added to HtmlForm along with it.
    – teenup
    Jun 14, 2011 at 13:08
  • this will not work if your grid is inside an .ascx user control. in that case see Chris Mullins answer below. I have used both Tim and Chris's techniques and they work great. Mar 12, 2014 at 21:15
  • 4
    Worked great. Just a heads up you may get an error saying "RegisterForEventValidation can only be called during Render();" If so set make sure to set the EventValidation to false in the markup for the page. Jul 2, 2014 at 16:14
30

An alternative to overriding VerifyRenderingInServerForm is to remove the grid from the controls collection while you do the render, and then add it back when you are finished before the page loads. This is helpful if you want to have some generic helper method to get grid html because you don't have to remember to add the override.

Control parent = grid.Parent;
int GridIndex = 0;
if (parent != null)
{
    GridIndex = parent.Controls.IndexOf(grid);
    parent.Controls.Remove(grid);
}

grid.RenderControl(hw);

if (parent != null)
{
    parent.Controls.AddAt(GridIndex, grid);
}

Another alternative to avoid the override is to do this:

grid.RenderBeginTag(hw);
grid.HeaderRow.RenderControl(hw);
foreach (GridViewRow row in grid.Rows)
{
    row.RenderControl(hw);
}
grid.FooterRow.RenderControl(hw);
grid.RenderEndTag(hw);
4
  • Adroit!! I will try it tomorrow.
    – teenup
    Jun 14, 2011 at 19:06
  • when trying to render the grid inside an asp user control (.ascx), using the 1st method worked great for me. Mar 12, 2014 at 21:13
  • 3
    1.It doesn't work if gridview contains controls like LinkButton - it gives 'Control of type 'LinkButton' must be placed inside a form tag with runat=server' error. 2.Could you please explain why does this technique work?
    – BornToCode
    Nov 4, 2015 at 13:01
  • @BornToCode Disable sorting for your gridview in code.
    – Adi Solar
    Feb 28, 2017 at 13:04
14

Just after your Page_Load add this:

public override void VerifyRenderingInServerForm(Control control)
{
    //base.VerifyRenderingInServerForm(control);
}

Note that I don't do anything in the function.

EDIT: Tim answered the same thing. :) You can also find the answer Here

2

Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.

You actually can do this but it's a bit of a bodge.

First off create a new Page class which looks something like the following:

public partial class NoRenderPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    { }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //Allows for printing
    }

    public override bool EnableEventValidation
    {
        get { return false; }
        set { /*Do nothing*/ }
    }
}

Does not need to have an .ASPX associated with it.

Then in the control you wish to render you can do something like the following.

    StringWriter tw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(tw);

    var page = new NoRenderPage();
    page.DesignerInitialize();
    var form = new HtmlForm();
    page.Controls.Add(form);
    form.Controls.Add(pnl);
    controlToRender.RenderControl(hw);

Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.

2
  • @DanielEdwards what does DesignerInitialize() do for you?
    – JJS
    Jun 10, 2016 at 16:16
  • This works but I needed to use HttpContext.Current.Server.Execute(page, writer, false); to write the HTML - calling controlToRender.RenderControl(hw); didn't raise any of the controls events e.g Page_Load so whilst the control was rendering, it was empty.
    – DGibbs
    Jun 10, 2019 at 11:11
0

Here is My Code

protected void btnExcel_Click(object sender, ImageClickEventArgs e)
    {
        if (gvDetail.Rows.Count > 0)
        {
            System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
            gvDetail.RenderControl(htmlWrite1);

            gvDetail.AllowPaging = false;
            Search();
            sh.ExportToExcel(gvDetail, "Report");
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }
1
  • Why did you add this answer 5 years after it was answered? And it is the same answer.
    – Mukus
    May 23, 2018 at 4:03
0

Tim Schmelter's answer helped me a lot, but I had to do one more thing to get it to work on my aspx page. I am using this code to email an embedded GridView control (as HTML), for report automation.

In addition to adding the override sub, I had to do the render() in Me.Handles.onunload, or else I got an error on the RenderControl line.

Protected Sub Page_After_load(sender As Object, e As EventArgs) Handles Me.Unload
If runningScheduledReport Then

    Dim stringBuilder As StringBuilder = New StringBuilder()
    Dim stringWriter As System.IO.StringWriter = New System.IO.StringWriter(stringBuilder)
    Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(stringWriter)
    GridView1.RenderControl(htmlWriter)
    Dim htmlcode As String = stringBuilder.ToString()
    
    Func.SendEmail(Context.Request.QueryString("email").ToString, htmlcode, "Auto Report - Agent Efficiency", Nothing)

End If
End Sub

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.