Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting DataSource in GridView after PostBack

So I have a GridView in my ASPX page.

When I click <asp:Button id="btnBindIt" runat="server" /> it binds a datatable as follows:

theDataTable = GetAllTheRecords();
gvTheGridView.DataSource = theDataTable;
gvTheGridView.DataBind();

Note: theDataTable is a member

private DataTable theDataTable;

This works as expected.

Now, after the GridView is displayed nicely, I want to export the data to CSV, so I now click the <asp:Button id="btnExportIt" runat="server" /> which runs the code:

exportToCsv(theDataTable);

but theDataTable is null.

So I tried

exportToCsv(gvTheGridView.DataSource)

Which is also null.

What's the standard way of persisting this data? I don't really want to hit the DB again as it's quite a long SPROC and the user has already waited once.

Thanks in advance!

like image 982
Ev. Avatar asked May 25 '11 04:05

Ev.


1 Answers

Class level variables can't maintain their value on postback.

But there are two ways you can maintain Data on the Page's PostBack: ViewState and Session State. But I would suggest in your Scenario to put it in the ViewState.

ViewState["theDataTable"] = theDataTable;
Session["theDataTable"] = theDataTable;

And then you can access it on the page postback:

DataTable theDataTable = (DataTable)ViewState["theDataTable"];
DataTable theDataTable = (DataTable)Session["theDataTable"];
like image 79
Muhammad Akhtar Avatar answered Sep 25 '22 14:09

Muhammad Akhtar