Please take a look at the following click event...
Protected Sub btnDownloadEmpl_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDownloadEmpl.Click
Dim emplTable As DataTable = SiteAccess.DownloadEmployee_H()
Dim d As String = Format(Date.Now, "d")
Dim ad() As String = d.Split("/")
Dim fd As String = ad(0) & ad(1)
Dim fn As String = "E_" & fd & ".csv"
Response.ContentType = "text/csv"
Response.AddHeader("Content-Disposition", "attachment; filename=" & fn)
CreateCSVFile(emplTable, Response.Output)
Response.Flush()
Response.End()
lblEmpl.Visible = True
End Sub
This code simply exports data from a datatable to a csv file. The problem here is lblEmpl.Visible=true never gets hit because this code doesnt cause a postback to the server. Even if I put the line of code lblEmpl.Visible=true at the top of the click event the line executes fine, but the page is never updated. How can I fix this?
This line:
lblEmpl.Visible = True
Never gets hit because this line:
Response.End()
Throws a ThreadAbortException
I think a cleaner way to handle this is to create a simple HttpHandler component, and 'open' it in a popup window. (The popup window shouldn't actually open. In most cases the browser will realize it's actually a download, and will suppress the tab/window.)
Research the IHttpHandler interface. They're actually quite simple to implement.
Here's a sample handler. Sorry it took awhile, I got called into a meeting:
public class CensusHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string fileName = String.Format(
CultureInfo.CurrentUICulture,
"E_{0:00}{1:00}.csv",
DateTime.Today.Month,
DateTime.Today.Day
);
context.Response.ContentType = "text/csv";
context.Response.AddHeader(
"Content-Disposition", String.Format(null, "attachment; filename={0}", fileName)
);
//Dump the CSV content to context.Response
context.Response.Flush();
}
public bool IsReusable { get { return false; } }
}
OK, try adding a javascript onclick event to trigger the download:
<asp:Button ID="Clickety" runat="server" Text="Click Me!" OnClick="Clickety_Click"
OnClientClick="window.open('Handler.ashx', 'Download');" />
The regular OnClick event will fire your postback code. The javascript onclick (OnClientClick) event will launch the download via the HttpHandler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With