Tag Archives: CSV

Using a data grid in C# / WPF is a pleasure…unless you want to export the data in the grid to a CSV (comma-separated) file (and you don’t know this trick)! What happens is you likely Google something like ‘wpf datagrid export to csv’ and Google provides you with a bunch of results, all articles telling you how to parse through the data-grid, extracting and writing the data from the grid one row, one cell at a time. Now if that’s all you see, it actually starts looks pretty complicated to get the data into a CSV file! Luckily, you are here. 🙂

There is what could reasonably be called a really great shortcut to actually exporting the data out of the WPF data-grid, that doesn’t require looping through, or otherwise manipulating the data-grid in any way.

Copying the data:

The WPF data-grid has the SelectAllCells and UnselectAllCells methods. These methods together with the ApplicationCommands type gives us a way to select all the data, and copy it to the Windows Clipboard. This is just as you would have done if you had selected all the cells of the datagrid with your mouse, and pressed ctrl-c on your keyboard:

Now the data is copied to the clipboard (notice how this means this method won’t be that great for data files that have gigabytes of data 😉 ) – and that’s it! The scary part is over! You have exported the data from the grid!!! Ok, well, you’ve still only exported it to the Windows Clipboard, so…

Writing the data:

Now you simply need to get the data from the Clipboard, and write it out to a file and you’re done!