e-on
e-on

Reputation: 1605

export datatable to CSV with Save File Dialog box - C#

Struggling to get my CSV export to display the Save File dialog box up. It saves to file ok, but doesn't let the user save. Can anybody see where I might be going wrong with the code please?

string filename = Server.MapPath("~/download.csv");
StreamWriter sw = new StreamWriter(filename, false);

int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
    sw.Write(dt.Columns[i]);
    if (i < iColCount - 1)
    {                
        sw.Write(",");
    }
}
sw.Write(sw.NewLine);

foreach (DataRow dr in dt.Rows)
{
    for (int i = 0; i < iColCount; i++)
    {
        if (!Convert.IsDBNull(dr[i]))
        {
            sw.Write(dr[i].ToString());
        }
        if (i < iColCount - 1)
        {
            sw.Write(",");
        }
    }
    sw.Write(sw.NewLine);
}
sw.Close();

Response.Clear();
Response.ContentType = "application/csv";
Response.AddHeader("Content-Disposition", "attachment; filename=download.csv");
Response.WriteFile(filename);
Response.Flush();
Response.End();

I thought the Content Disposition line that brought up the dialog box, but maybe there is something else I need to do.

Thanks

Upvotes: 0

Views: 11414

Answers (3)

e-on
e-on

Reputation: 1605

Ah, have discovered what the problem is...

I've got the button in an update panel and didn't realise the response object doesn't work in an update panel.

I made the download button a trigger, and it now works great.

<Triggers>
    <asp:PostBackTrigger ControlID="btnDownload" />
</Triggers>

Thanks for the suggestions anyway

Upvotes: 2

DaveB
DaveB

Reputation: 9530

You could try clearing the content and the headers after your Response.Clear() call:

    Response.ClearContent();
    Response.ClearHeaders(); 

Upvotes: 0

Eric Robinson
Eric Robinson

Reputation: 2095

I'm pretty sure you need

Response.Write()

after

Response.End()

Upvotes: 0

Related Questions