I want to covnvert GridView data to Excel sheet.
I have written the code below, but it gives error:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Avukat.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
Response.Write(stringWrite.ToString());
Response.End();
}
Error:
Control 'ctl00_ContentPlaceHolder1_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
I think your gridview contains a linkbutton/Imagebutton or another type of control
, and that's why you are getting an Exception when you are trying to export the GridView to Excel.
Before using the control you need to add the following lines in your Page code behind, or the BasePage code behind.
public override void VerifyRenderingInServerForm(Control control)
{
}
You can use this code, as this code is tested and worked perfectly:
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
Response.AddHeader("content-disposition", "attachment; filename=Avukat.xls");
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With