Hi,
i want export gridview data to excel,i am trying to export and it's working in aspx page but when i am using same code in web user control(ascx) page , it's not working.
even i tried to override VerifyRenderingInServerForm in my aspx page where i am binding user control also not working.
public override void VerifyRenderingInServerForm(Control control) { }
refer the below where i am doing wrong.let me know if have any other idea to export to excel/pdf
protected void ExporttoExcel_Click(object sender, EventArgs e)
{
ExporttoExcel();
}
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;
// BindGridDetails(GridView1);
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 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();
}
protected void BindingGridView_Click(object sender, EventArgs e)
{
BindGridDetails();
}
let me know if you need more information.
Thanks