Dimi Dimi - 1 year ago 65
ASP.NET (C#) Question

Download file and populate Grid in ASP.NET at the same time

I try to use a ASP.NET button event to do two things are

  1. Populate a Grid

  2. Download/Export a file

The code I have got sends the file with correct data but

A. Grid is not populated

B. There is an exception

Any clue how to fix it?

protected void ButtonExportCSV_Click(object sender, EventArgs e)
... Getting startDate, endDate
List<WorkOrder> result = GetWorkOders(startDate, endDate); // It populates Grid using GridViewWorkOrders.DataSource = result; GridViewWorkOrders.DataBind();

string csv = DataHelper.ToCsv(";", result);

var filename = "WorkOrders-ingresados-" + DateTime.Now.ToString("ddMMyyyy-HHmmsss");


Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".csv");
Response.End(); // The exception occurs here
catch (Exception ex)


enter image description here


I could get rid of the exception replacing

HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.

but anyway grid is not populated.

ANy clue if it is possible at all?

Answer Source

ok. i think the the issue is

you are trying to send multiple Content-Type in single response which is not possible

  1. to populate Grid, server need to send html so the Content-Type: text/html

  2. to download a file Content-Type: text/csv

in your code you are overriding the text/html (which is default when GridView.DataBind() called) with text/csv

so the grid view html will be erased and csv content will be attached to response


first send GridView Bind response without the csv file

then once page loaded with new Grid, call a script function which calls a method in server to download csv file

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download