>I am tasked to add a CSV export option to an HTML report I have in ASPX.
>Data is in a DataTable and HTML is built manually (more control than with a DataGrid/GridView)
>
>I added a hyperlink to the webpage as follows:
>
>< asp:LinkButton ID="btnExport" runat="server" Width="114px">Export Report< /asp:LinkButton>
>
>What I see is the link when pressed, does a PostBack to he same page. I want to call my ExportDataToCSV() below:
>
>public bool ExportDataToCSV(DataTable oSourceTable, string sFileName, string sDelimiter, Boolean IsWriteColumnHeaders)
>{
> // TODO: loop through rows and columns creating delimited strings
> // then send to the client through HTTP
>}
>
>Questions: Is there a better way to do this than through a Postback?
>If a Postback,
>a. how do I pass the DataTable to the method call? (as ViewState is kinda wasteful and would have to be cast a DataTable - how do I do that?)
>b. if DataTable is passed directly as a parameter (better than through HTTP IMO), how do I accomplish that from the LinkButton?
>
>Hope I'm clear enough. Now back to battling with C# <g>
>
>[UPDATE]: as I'm already looping through the DataSet when building an HTML table I could also build a CSV at the same time then pass it as a string and avoid passing a DataSet (makes it easier through PostBack?).
>Drawbacks: It might be a large string. It is extra work done every time when they may only want to download a CSV copy of the HTML table every so often.
>
>Thoughts?
I can't tell if part of your question is how to get your method to execute when someone clicks on the LinkButton, and I would guess you already know how, but just in case:
- go to the Properties/Events of the button
- enter an event handler name e.g. btnExport_OnServerClick for the Click event
- Visual Studio will create and hook up the event handler code for you
Postback vs. non-postback: if it isn't a postback it has to run on the client. I haven't done any client side scripting but I understand you'd need to look into JavaScript. Another issue would be that unless the data you're going to export are already on the client you'd have to get them there somehow to be processed client-side.
If you want to do it server-side using a DataTable, you can:
- re-create the DataTable in the Export method
- persist the DataTable from an earlier method, and use that
If the latter, I agree with Bonnie, using Session state is one way to persist the DataTable e.g.
Session["MyDataTable"] = dt;
DataTable dt = (DataTable)Session["MyDataTable"];
You'll have to decide if saving the DataTable in Session state is reasonable (not too large, won't hang around too long) and also remember to destroy it when you're finished with it.
Regards. Al
"Violence is the last refuge of the incompetent." -- Isaac Asimov
"Never let your sense of morals prevent you from doing what is right." -- Isaac Asimov
Neither a despot, nor a doormat, be
Every app wants to be a database app when it grows up