0

I want to export DataTable data to excel and download it to a client drive location. My code is as follows:

protected void ExportDatatable()
    {
        DataTable dt = new DataTable();
        string errorMsg = string.Empty;
        dt = null;
        CnSServer cnsServer = new CnSServer();
        string str = string.Empty;

        try
        {

            string query = @"SELECT * FROM Products";


            dt = cnsServer.GetShortSaleReport(query, out errorMsg);

            Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment;filename=MyExcellData.xls", DateTime.Now.ToString("yyyy-MM-dd")));
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";
            foreach (DataColumn dataColumn in dt.Columns)
            {

                str += dataColumn.ColumnName + "\t";
            }

            str += "\n";

            int i;
            foreach (DataRow dataRow in dt.Rows)
            {

                str += dataRow["ID"] + "\t";
                str += dataRow["ProductCode"] + "\t";
                str += dataRow["ProductName"] + "\t";                
                str += "\n";                    

            }
            Response.Write(str);                
            Response.End();
        }
        catch (Exception e)
        {
            errorMsg = e.ToString();            
        }                           
            return dt;

    }

This gives me error message ''unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.' No file is downloaded. But DataTable has data inside it. I have don't find any proper solution in this regard. Any suggestions. Thanks in advance.

  • 1
    I just copypasta the error message in my favorite google. Does this answer your question? [Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack](https://stackoverflow.com/questions/2041482/unable-to-evaluate-expression-because-the-code-is-optimized-or-a-native-frame-is) – Orace Jan 27 '20 at 08:33
  • don't catch the exception, let it fail and debug it – Icepickle Jan 27 '20 at 09:37

0 Answers0