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.
You can use this code, as this code is tested and worked perfectly: