WPF Data grid to CSV and HTML the easy way |
Written by Mike James | |||
Thursday, 11 November 2010 | |||
Page 1 of 2 The WPF DataGrid can be a difficult beast to tame but it has a lot of built in power and once you get to understand the way that it works it can save you a lot of code and a lot of time.
If you are new to the WPF Data Grid refer to: Using the WPF .NET 4.0 DataGrid
Accessing grid dataOne fairly common requirement is to take data that is stored in the grid, usually as the result of some data processing, and load it into another applications such as Excel or a statistical analysis tool. In an ideal world we would expect to make use of something sophisticated data exchange format but in the real world something simple like Comma Separated CSV values or at best HMTL. are often more practical choices. So how best to get data out of the DataGrid and into CSV or HTML?
Along the way we learn a little about the clipboard and a little about WPF commands. A little dataFirst we need some data to test the program with. Rather than invent a complicated database scenario we can simply create some data and load it into a suitable grid. First we need a simple struct that we can use to define the data items: public struct MyData
We can use object initialisation fo add the data to the DataGrid's Items collection: dataGrid1.Items.Add(new MyData() { At this point we have the data in the grid but it doesn't know what the structure of the data is. To define this we need to add two Text columns and bind the columns to the struct's properties: DataGridTextColumn col1 = Finally we can add headers to the columns and add them to the DataGrid: col1.Header = "Name"; Now if you run the program you will see a DataGrid with a small amount of data suitable for testing: <ASIN:0470477229> <ASIN:0672330334> <ASIN:0596159838> <ASIN:1430226501>
|
|||
Last Updated ( Thursday, 11 November 2010 ) |