System.Threading.ThreadAbortException occurred in mscorlib.dll occuring persitently

Im new to .net, Im using the following code to transfer from gridview to excel:

         protected void toexcelbutton_Click(object sender, EventArgs e)
        {
       Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "attendancedatereport.xls"));
    Response.ContentType = "application/ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.AllowSorting = false;
    GridView1.DataBind();
    HtmlForm htmfrm = new HtmlForm();
    GridView1.Parent.Controls.Add(htmfrm);
    htmfrm.Attributes["runat"] = "server";
    htmfrm.Controls.Add(GridView1);
    htmfrm.RenderControl(htw);
    Response.Write(sw.ToString());

    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

When i run this code,i get an exception:

A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll.

But,when i run the same code in another page for another gridview,it works perfectly.,i tried,adding

EnableEventValidation="false"

to the aspx page, and

<pre lang="cs">public override void VerifyRenderingInServerForm(Control control)
{
   /* Verifies that the control is rendered */
}</pre>

to the aspx.cs page,

i tried clearing the temporary files, still i get the same error,for more than 5hours i have tried,nothing is working.

I then tried select the Debug -> Exceptions menu item, and in the dialog that appears, checked the first checkbox for "Common Language Runtime Exceptions,

i get this error:

Access to the path 'C:\Users\abcd\AppData\Local\Temp\Temporary ASP.NET Files\mark\3f229106\f785abea\App_Web_0h5ppn4m.dll' is denied.

Jon Skeet
people
quotationmark

Yes, it will happen due to this:

Response.End();

As documented:

To mimic the behavior of the End method in ASP, this method tries to raise a [ThreadAbortException] exception. If this attempt is successful, the calling thread will be aborted, which is detrimental to your site's performance. In that case, no code after the call to the End method is executed.

So your Response.Clear call is pointless - and you should expect to see the ThreadAbortException, which you can ignore in this case.

If you need to call Response.Clear at all, it should be before you write to it - but I suspect you're fine to just remove it entirely.

people

See more on this question at Stackoverflow