In the past, I have populated GridView's with 'manually created' data sources in the code behind, by doing this in the Page Load:
DataTable myData = SomeMethod(); //Returns a DataTable
myGrid.DataSource = myData;
myGrid.DataBind();
and whenever I wanted to download the data to a CSV file, I'd just add the following to the button's Click event:
DataTable csvData = new DataTable();
csvData = (DataTable)myGrid.DataSource;
//CSV construction, reponse send to browser, etc.
This works because the GridView is already databound during Page Load, so the data is available when the Click event is reached.
But now I can't get it to work using a SqlDataSource control that I added in design time (HTML). This SqlDataSource is bound to a DropDown control with auto-postback, so that data is retrieved when the selection is changed.
I run the website, with data already displayed in the GridView (EnableViewState=false to force query at each page load), and click the button, only to get an exception caused by the fact that myGrid.DataSource is null.
My question (finally): I've noticed that the click event occurs before GridView_OnDataBound, but even OnDataBound the datasource is null. How can I get the data from the rendered GridView to allow the donload? Or from where should I attempt to retrieve it?