I am attempting to export a datagrid to excel via a popup. I am able to successfully export to excel when removing the code from my application, however, when attempting to export to excel using the exact same code within my application, I receive the following errors:
From my try/catch:
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
...and from the console:
Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.
My server-side code is as follows:
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
ExportDataSetToExcel();
}
private void ExportDataSetToExcel()
{
try
{
DataTable dt = new DataTable("GridView_Data");
foreach (TableCell cell in gvPatientRoster.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in gvPatientRoster.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
}
}
if (dt != null && dt.Rows.Count > 0)
{
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename=PatientRoster.xls"));
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw =
new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
//Report Header
hw.WriteLine("<b><u><font size='5'>" +
"Patient Roster</font></u></b>");
hw.WriteLine("<br><br>");
//hw.Write(BuildCriteriaString());
hw.WriteLine("<br>");
// Get the HTML for the control.
dgGrid.HeaderStyle.Font.Bold = true;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
// Write the HTML back to the browser.
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
catch (Exception ex)
{
lblErrorMessage.Text = ex.Message;
}
}