Hi,
I have a grid view and want to export gridview data to excel. I am using SQLdatasource connection.
Here is my .CS code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- using System.IO;
- using System.Drawing;
- namespace Camden_Homes
- {
- public partial class LLC : System.Web.UI.Page
- {
- static string previouspage = string.Empty;
- protected void Page_Load(object sender, EventArgs e)
- {
- if (Session["username"] == null)
- Response.Redirect("default.aspx");
- Label1.Text = "username: " + Session["username"];
- }
- protected void LinkButton1_Click(object sender, EventArgs e)
- {
- Response.Redirect(previouspage);
- }
- protected void LinkButton2_Click(object sender, EventArgs e)
- {
- Response.Redirect("default.aspx");
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- Response.Clear();
- Response.Buffer = true;
- Response.AddHeader("content-disposition", "attachment;filename=camdenexport.xls");
- Response.Charset = "";
- Response.ContentType = "application/vnd.ms-excel";
- using (StringWriter sw = new StringWriter())
- {
- HtmlTextWriter hw = new HtmlTextWriter(sw);
- GridView1.HeaderRow.BackColor = Color.White;
- foreach (TableCell cell in GridView1.HeaderRow.Cells)
- {
- cell.BackColor = GridView1.HeaderStyle.BackColor;
- }
- foreach (GridViewRow row in GridView1.Rows)
- {
- row.BackColor = Color.White;
- foreach(TableCell cell in row.Cells)
- {
- if (row.RowIndex % 2 ==0)
- {
- cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
- }
- else
- {
- cell.BackColor = GridView1.RowStyle.BackColor;
- }
- cell.CssClass = "textmode";
- }
- }
- GridView1.RenderControl(hw);
- string style = @" .textmode { } ";
- Response.Write(style);
- Response.Output.Write(sw.ToString());
- Response.Flush();
- Response.End();
- }
- }
- public override void VerifyRenderingInServerForm(Control control)
- {
-
- }
- }
- }
And I am getting error is
RegisterForEventValidation can only be called during Render();
Description: 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.
Exception Details: System.InvalidOperationException: RegisterForEventValidation can only be called during Render();
Source Error:
Line 63: }
Line 64: }
Line 65: GridView1.RenderControl(hw);
Line 66: string style = @" .textmode { } ";
Line 67: Response.Write(style);