Hi Sudar,
Check this example. Now please take its reference and correct your code.
There is no need to override the VerifyRenderingInServerForm.
ExportGrid.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ExportGrid.ascx.cs" Inherits="ExportGrid" %>
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Id" />
<asp:BoundField DataField="Student_Name" HeaderText="Name" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
</asp:GridView>
<br />
<asp:Button Text="Export" runat="server" OnClick="ExporttoExcel_Click" />
ExportGrid.ascx.cs
public partial class ExportGrid : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
BindGridDetails();
}
protected void BindGridDetails()
{
DataTable dt = new DataTable();
dt.Columns.Add("StudentID", typeof(Int32));
dt.Columns.Add("Student_Name", typeof(string));
dt.Columns.Add("City", typeof(string));
DataRow dtrow = dt.NewRow();
dtrow["StudentID"] = 1;
dtrow["Student_Name"] = "Rakesh";
dtrow["City"] = "Delhi";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();
dtrow["StudentID"] = 2;
dtrow["Student_Name"] = "Suresh";
dtrow["City"] = "Mumbai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();
dtrow["StudentID"] = 3;
dtrow["Student_Name"] = "Samir";
dtrow["City"] = "Bangalore";
dt.Rows.Add(dtrow);
GridView1.DataSource = dt;
GridView1.DataBind();
}
private void ExporttoExcel()
{
BindGridDetails();
HtmlForm form = new HtmlForm();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", "Student.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
form.Attributes["runat"] = "server";
form.Controls.Add(GridView1);
this.Controls.Add(form);
form.RenderControl(hw);
string style = @"<style> .textmode { mso-number-format:\@;}</style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
protected void ExporttoExcel_Click(object sender, EventArgs e)
{
ExporttoExcel();
}
}
Default.aspx
Using the UserControl in page.
<%@ Register Src="~/ExportGrid.ascx" TagName="gvStudents" TagPrefix="uc" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc:gvStudents ID="ucGridView" runat="server" />
</div>
</form>
</body>
</html>
Screenshot
