i have this code
it keeps giving me error
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim response As HttpResponse = HttpContext.Current.Response()
response.Clear()
response.AddHeader("content-disposition", "attachment;filename=XXXXXX.xls")
response.ContentType = "application/vnd.ms-excel"
Dim s As System.IO.StringWriter = New System.IO.StringWriter
Dim htw As HtmlTextWriter = New HtmlTextWriter(s)
GridView1.RenderControl(htw)
response.Write(s.ToString)
response.End()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)
End Sub
the error is after i click on export : RegisterForEventValidation can only be called during
Render();
and it highlight this script
GridView1.RenderControl(htw)
any advices
Disable event validation on page level:
<%@ Page Language="VB" AutoEventWireup="false" EnableEventValidation="false" ...
But i would suggest creating a real excel file and write that binary to the stream instead of a HTML table. EppPlus is highly recommended, easy to use and supports LINQ. (GPLv2).
** Copy Paste the below coding and test your output ** before that Add Reference to Microsoft Excel 11.0 Object Library/Microsoft Excel 12.0 Object Library/Microsoft Excel 14.0 Object Library
String fileName ="GVtoExcel";
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs(fileName);
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);
ExcelApp = null;