How can I export a GridView.DataSource to a datatable or dataset? How can I export a GridView.DataSource to a datatable or dataset? asp.net asp.net

How can I export a GridView.DataSource to a datatable or dataset?


Assuming your DataSource is of type DataTable, you can just do this:

myGridView.DataSource as DataTable


You should convert first DataSource in BindingSource, look example

BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource DataTable tCxC = (DataTable) bs.DataSource;

With the data of tCxC you can do anything.


Personally I would go with:

DataTable tbl = Gridview1.DataSource as DataTable;

This would allow you to test for null as this results in either DataTable object or null. Casting it as a DataTable using (DataTable)Gridview1.DataSource would cause a crashing error in case the DataSource is actually a DataSet or even some kind of collection.

Supporting Documentation: MSDN Documentation on "as"