Search code examples
c#asp.netexport-to-excel

"Unable to evaluate expression because the code is optimized or a native frame is on top of the stack" while export the grid into excel


Getting an error while exporting the selected rows of grid into excel. error: Unable to evaluate expression because the code is optimized or a native frame is on top of the stack.

Actually I want to export the selected rows from the grid to excel, so the user can easily download the selected records please refer the code for Export to excel Onclick method.

protected void btnExportExcel_Click(object sender, EventArgs e)
    {
                bool isSelected = false;
                foreach (GridViewRow i in gvDistrictSchoolReport.Rows)
                {
                    CheckBox cb = (CheckBox)i.FindControl("Chkbox");
                    if (cb != null && cb.Checked)
                    {
                        isSelected = true;
                        break;
                    }
                }
                if (isSelected)
                {
                    GridView gvExport = gvDistrictSchoolReport;
                    // this below line for not export checkbox to excel file
                    gvExport.Columns[0].Visible = false;
                    foreach (GridViewRow i in gvDistrictSchoolReport.Rows)
                    {
                        gvExport.Rows[i.RowIndex].Visible = false;
                        CheckBox cb = (CheckBox)i.FindControl("Chkbox");
                        if (cb != null && cb.Checked)
                        {
                            gvExport.Rows[i.RowIndex].Visible = true;
                        }
                    }
                    try
                    {
                        Response.Clear();
                        Response.Buffer = true;
                        Response.AddHeader("content-disposition", "attachment;filename=ExportGridData.xls");
                        Response.Charset = "";
                        Response.ContentType = "application/vnd.ms-excel";
                        StringWriter sw = new StringWriter();
                        HtmlTextWriter htW = new HtmlTextWriter(sw);
                        gvExport.RenderControl(htW);
                        Response.Output.Write(sw.ToString());
                        Response.Flush();
                        Response.End();

                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine(ex);
                    }

                }
            }

Solution

  • If you are using update panel then use PostBack Triggers like this

    <asp:UpdatePanel ID="up1" runat="server">
            <Triggers>
            <asp:PostBackTrigger ControlID="gvDistrictSchoolReport" /> -- for grid
                 <asp:PostBackTrigger ControlID="Button6" />  -- for export to excel button
        </Triggers>
    

    before the grid. Hope this will work