get DataTable or DataSet from a WPF DataGrid?

Sep 14, 2009 at 5:51 PM

I've got the need to export the contents of a WPF DataGrid to Excel. I have code working (thanks to people on here!) to export it to .CSV file using the DataGridClipboardCopyMode, etc. However, a new requirement is that it saves as an Excel (xls) file. (!) I have code working that transforms ListViews to Excel using Excel automation. I get the DataTable from the ListView and iterate through it, exporting the data to Excel via Excel automation.

So my question is, is it possible to get a DataTable from the contents of the DataGrid?  All I'd need to get from the DataGrid is a DataSet,  DataView or GridView object, then I can get the rest from there.

Thanks in advance for your help!


Sep 17, 2009 at 9:10 PM

anyone ever run into this? I"m populating my DataGrid (it's ItemsSOurce) with a collection of objects,

Sep 18, 2009 at 9:18 PM

Hi CCusson15, how are you getting the DataTable from ListView?  If you could post code snippets or be more descriptive, I think we'd have more info to better help you with your scenario.


Sep 18, 2009 at 10:06 PM

Hi Saied,

Here's my code on how I get the DataTable out of the ListView. In this case, the e.Source is passed in via a button click on the ListView. We added an 'Export' button to the ListView to support exporting the data to Excel.




ListView lvResults = e.Source as ListView;
GridView view = lvResults.View as GridView;

System.Data.DataView theView = ((System.Data.DataRowView)lvResults.Items[0]).DataView;

System.Data.DataTable dt = theView.Table;

Sep 18, 2009 at 10:21 PM

Did you try 

DataView dView = dataGrid.ItemsSource as DataView;

This will work incase you are setting your ItemsSource in that respect.

Sep 18, 2009 at 10:39 PM

I'm binding  a collection of 'business objects' (one of many different classes) to the DataGrid's ItemsSource, so this cast into a DataView will not work

Sep 28, 2009 at 7:35 PM

any other ideas?