views:

15

answers:

1

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?

+1  A: 

When using design time data sources, the DataSource property is not used. Instead the DataSourceID property is used, but all it contains is the name of the data source control. You will have to go back to your SQLDataSource to get the information you need for exporting.

DataView dv = (DataView)sqlDataSource.Select(DataSourceSelectArguments.Empty); 
DataTable dt = dv.ToTable(); 
Jason Berkan
I just tried it and it worked flawlessly. I usually work with manually created datasource objects, but this time I needed a fully functional (sortable, page-able) GridView and I didn't want to spend too much time creating and handling events. Thanks!
PJ