I am trying to export gridview contents into Excel as given below, Excel is created but there is no content. but I am able to view the content in the webpage.
Response.Clear();
Response.Buffer = true;
string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls";
Response.AddHeader("content-disposition",
"attachment;filename=" + filename);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.AllowPaging = false;
gv.DataBind();
gv.RenderControl(hw);
//style to format numbers to string
string style = @"";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
//verifies that the control is rendered
}
Loading
JAYRAMPosted Feb 4, 2013, 12:47 PM
Dscription: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.error
RegisterForEventValidation can only be called during Render();
Exception Details: System.InvalidOperationException: RegisterForEventValidation can only be called during Render();
Source Error:
JAYRAMPosted Feb 4, 2013, 5:23 AM
Rishikesh Kumar SinghPosted Feb 4, 2013, 5:04 AM
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
//Change the Header Row back to white color
gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
{
gvdetails.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
If it helps you then mark it as an accepted answer otherwise let me know..!!