开发者

How to download GridView data after data binding?

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?


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(); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜