在PostBack之后在GridView中保留DataSource

所以我在ASPX页面中有一个GridView。

当我单击它会绑定数据表,如下所示:

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

注意: theDataTable是一个成员

 private DataTable theDataTable; 

这按预期工作。

现在,在很好地显示GridView之后,我想将数据导出为CSV,所以我现在单击运行代码的

 exportToCsv(theDataTable); 

theDataTable为null。

所以我试过了

 exportToCsv(gvTheGridView.DataSource) 

哪个也是null。

持久化这些数据的标准方法是什么? 我真的不想再次点击数据库,因为它是一个相当长的SPROC并且用户已经等了一次。

提前致谢!

类级变量无法在回发时保持其值。

但是有两种方法可以在页面的PostBack上维护数据: ViewState and Session State 。 但我建议在你的场景中将它放在ViewState

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

然后你可以在页面上回访它:

 DataTable theDataTable = (DataTable)ViewState["theDataTable"]; DataTable theDataTable = (DataTable)Session["theDataTable"]; 

声明数据表如下,一切都将按预期工作

  private string _theDataTable="theDataTable"; private DataTable theDataTable { get { if(ViewState[_theDataTable]==null) return new DataTable(); return (DataTable)ViewState[_theDataTable]; } set { ViewState[_theDataTable] = value; } } 

干杯!

谢谢大家的答案。

我避免将内容放入VeiwState或会话中,因此我认为保留此数据的最佳方法是缓存它。

我认为MemoryCache是最合适的地方,就是我最终实现它的方式。