0

Guys I searched in internet and found many solutions for exporting gridview to excel. I tried all the solutions but none of them worked for me. As suggested I traced the Application_Error module.

While debugging my execution goes to

//Global.asax
protected void Application_Error(object sender, EventArgs e)
    {
        Exception exc = Server.GetLastError();
    }

The exception I am getting is :: Exception of type 'System.Web.HttpUnhandledException' was thrown.

I cannot figure out what am I doing wrong. Please can anyone suggest me, what is happening.

private void ExportGridToExcel()
        {
            try
            {
                Response.Clear();
                Response.Buffer = true;
                Response.ClearContent();
                Response.ClearHeaders();
                Response.Charset = "";
                string FileName = "PatientCount_" + DateTime.Now + ".xls";
                StringWriter strwritter = new StringWriter();
                HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
                GridView1.GridLines = GridLines.Both;
                GridView1.HeaderStyle.Font.Bold = true;
                GridView1.RenderControl(htmltextwrtter);
                Response.Write(strwritter.ToString());
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.SuppressContent = true;
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex) { }
        }

While debugging I am not getting any exceptions but after the execution of this code, the execution goes to Global.asax file Application_Error module.

Please help me!!!

user4221591
  • 2,084
  • 7
  • 34
  • 68

1 Answers1

1

Server.GetLastError() is your friend - use it in the Application_Error method to get the last encountered exception and see what you can learn from that. Look here for more details on handling application level errors such as this.

DrMistry
  • 321
  • 1
  • 13
  • Thanks for the help. I traced the code and edited my question. Please can you help me now. – user4221591 Sep 08 '16 at 12:50
  • I'm guessing you're using ASP.NET MVC? If you are, you can return a File object rather than hacking about with the response - you may find that easier and if it still fails, you should get a more meaningful exception. Have a look at [this SO question](http://stackoverflow.com/questions/3604562/download-file-of-any-type-in-asp-net-mvc-using-fileresult) as a starting point, that covers some common pitfalls and has some good solutions. Also, check for InnerExceptions on the exception you're getting in Application_Error – DrMistry Sep 08 '16 at 13:18