I have download link present in grid view and when I click on it, a save dialogue pop up will appeared and an Excel fill will be downloaded.
But I am getting error "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack." on Response.End()
.
Code :
protected void grdFiles_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "download")
{
string _FileName = Convert.ToString(e.CommandArgument);
//Response.Clear();
//Response.AppendHeader("Content-Disposition", "attachment; filename=" + _FileName);
//Response.ContentType = "application//octet-stream";
//Response.TransmitFile(Server.MapPath("~/Files/" + _FileName));
//Response.End();
// Get the physical Path of the file(test.doc)
string filepath = Server.MapPath("test.doc");
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(Server.MapPath("~/Files/" + _FileName));
// Checking if file exists
if (file.Exists)
{
// Clear the content of the response
Response.ClearContent();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
// Add the file size into the response header
Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
Response.ContentType = "application/vnd.ms-excel";
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
Response.TransmitFile(file.FullName);
// End the response
Response.End();
}
}
}
catch (Exception ex)
{
}
}
Best Answer
Another possible cause of this error, could possibly be because your grid is in an update panel?
If this is the case I would recommend that you add your grid control as a Post back trigger as such:
Though putting an entire grid as a Post back trigger might be overkill (post backs on paging might occur etc.), you could try creating your download link as a template column and set the control inside the grid as the post back trigger.
I had a similar problem where I used an Export button as a download button instead, and use the grid command to select a detail and make this button available only when something in the grid is selected then place a post back trigger on this button instead of having it on the grid.