I am trying to export a Gridview to excel. I bind the gridview to a collection and can see that it has 6 data rows but when i call the RenderControl it returns an empty string. Below is the code i am using
Gridview1.DataSource = data;
Gridview1.DataBind();
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
Gridview1.RenderControl(htw);
var outputHtml = sw.ToString();
when i check the outputHtml it is an empty string. What i am doing wrong in this piece of code.
One thing to note is that gridview is lying inside a form with runat=’server’ tag and i have not overridden the VerifyRenderingInServerForm method.
My best bet is that you have set the visibility of the GridView to false. This will prevent the control from rendering, because well…it’s invisible now. The result is an empty string.
If you don’t want to show the GridView, just set the Visibility to true before you execute your rendering code and set it back afterwards:
You possibly will run into trouble with the RenderControl method now. If so, make sure you have set
EnableEventValidation="false"in the Page directive and override theVerifyRenderingInServerFormmethod: