Generate Excel from Gridview when using Master page:
You can find many example of generating excel from Gridview.Those all are fines when we are not using master page.But when we use Masterpage & in the child page we have a gridview and we want to generate the excel from that grid view ,then we need to make some modification of these codes.Following are the example of that kind of code.
Step 1.Take a Gridview "GrdCommon" in your page & bind it from the server side code.
Step 2.Make a HTML table "tblExcelFirst" in any of the section of your HTML body.Dont Worry,that will not be displayed when you run your web page ,so it will not affect your output.
<table id="tblExcelFirst" runat="server">
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
Step 3.Write the following method in your server side code.
public void generateExcel()
{
string fileName = string.Empty;
HtmlForm frm = new HtmlForm();
this.Controls.Add(frm);
{
frm.Controls.Add(GrdCommon);
frm.Controls.Add(tblExcelFirst);
fileName = "MyReport";
}
Page.Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
frm.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.Flush();
Response.End();
}
Step 4.Call this method "generateExce" from your button click Event which will generate Excel from your gridview
Step5.If you get some error
RegisterForEventValidation can only be called during Render();
Then put the follwoing property in your page directive of your HTML page
EnableEventValidation="false"
ValidateRequest="false"
and your page directive will be looked like
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DetailReport.aspx.cs" Inherits="_DetailReport" MasterPageFile="~/Master/MasterPage2.master" Theme="Theme1" EnableEventValidation="false" ValidateRequest="false" % >
Search This Blog
Subscribe to:
Post Comments (Atom)
5 comments:
RegisterForEventValidation can only be called during Render();
this is the error it is giving?
excellent
I have sloved the error "Registration for evant validation" at the step 5
Excelent. 2 hours looking for this.
Thank you!
Thanks Claudia,please keep in touch
Post a Comment