2

I have a gridview on an aspx page.

the gridview already has a datasource and is populated.

i am trying to get the data out of it like this when the user clicks a button:

DataTable dt = (DataTable)grdList.DataSource;

however it is showing this result as null!

i understand this to be an issue with postback/viewstate.

can someone please recommend to me a solution by which i can get data out of the gridview?>

gsirianni
  • 1,334
  • 2
  • 18
  • 35
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

1 Answers1

4

No you cannot get the data from asp.net gridview. Instead use this code.

Datatable dt = SomeMethodReturningDataTable();

Viewstate["Table"] = dt;

GridView.DataSource = ViewState["Table"];
Gridview.DataBind();

If you want to make chnages, pull out the table from viewstate and make changes and then push it again and bind it to grid.

  • Why negative ? Any specific reason. –  Dec 08 '11 at 18:53
  • when i try to do this:Viewstate["Table"] = (DataTable)grdList.DataSource; i am getting 'viewstate' does not exist in current context – Alex Gordon Dec 08 '11 at 18:53
  • This would work but page size will grow depending on table size. I wouldnt go with this approach unless sure there are always only few records returned. – Davide Piras Dec 08 '11 at 18:55
  • 1
    You never get Datatable from the datasource. As the asp.net datasource is volatile in nature. See my suggestion.... in my answer. –  Dec 08 '11 at 18:56
  • @DavidePiras : You can have alternatives, 1. Sql Paging or 2.Compress the viewstate –  Dec 08 '11 at 18:57
  • @See-Sharp how do you compress viewstate? – Alex Gordon Dec 08 '11 at 19:24