Click here to Skip to main content
15,881,092 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i have tried the following code on my button click event but it shows an error as Control 'ctl00_ContentPlaceHolder1_grdsalarydetail' of type 'GridView' must be placed inside a form tag with runat=server. i have tried the same logic of code i asp.net with vb which works after adding an overrides method as


C#
Response.Clear();
        Response.AddHeader("Content-disposition", "Attachmen;filename=reports.xlsx");
        StringWriter StringWriter = new System.IO.StringWriter();
        HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);
        grdsalarydetail.RenderControl(HtmlTextWriter);
        Response.Write(StringWriter.ToString());
        Response.End();


but can any one explain in csharp how can i use the same code as i am not getting the correct logic of override method in csharp



XML
<b><pre lang="vb">Public Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)
        'MyBase.VerifyRenderingInServerForm(control)
    End Sub</pre>
</b>
Posted
Updated 3-Dec-12 4:34am
v3

private void ExportGridToExcel(GridView grdGridView, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition",
string.Format("attachment;filename={0}.xlsx", fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.xlsx";

StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

grdGridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
//You have to override this method
public override void VerifyRenderingInServerForm(Control control)
{

}
C#
<pre lang="c#">
 
Share this answer
 
Actually, there are a lot of solutions to export data from gridview to Excel. I am afraid people may not successfully reproduce your problem, so why do not try other solutions? they are easy to perform and at the same time, you can learn much from them. Here I can suggest you some, I believe they are helpful for you, you want simple code, so you can decide yourself which is the best
9 Solutions to Export Data to Excel for ASP.NET[^]
Export DataTable to Excel through DataGridView[^]
Excel to Datatable and Datatable to Excel[^]
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900