Accessing DataGrid data in C# with WPF

If you need to access row and column data values in a WPF DataGrid you’ll realize it is bit of a pain. It’s definitely easier to do this in WinForms but that may not be what you’re using. So here’s how you can access WPF DataGrid in your code:

Do note that I’ve used the actual data source of the DataGrid to retrieve data. This is probably a better idea than trying to read data values directly off of the DataGrid. Also, I’ve used reflection so you should add the ‘System.Reflection’ namespace.

1. First, to get column headers (separated by a blank space) from the DataGrid:

var gridHeaderData = string.Join(" ", MyDataGrid.Columns.Select(column => column.Header));

 

2. Get the binding paths from where your DataGrid columns get their data:

var bindingPaths = MyDataGrid.Columns.Select(column => ((Binding)(column as DataGridBoundColumn).Binding).Path.Path);

 

3. Now you have all you need to access the DataGrid data:

string gridData = new StringBuilder();
foreach (var item in MyDataGrid.ItemsSource)
{
    var properties = bindingPaths.Select(bindingPath => item.GetType().GetProperty(bindingPath)).ToArray();
    gridData.AppendLine(string.Join(" ", properties.Select(property => property.GetValue(item, null))));
}

 

You can also use the clipboard programmatically to get all of the data in MyDataGrid. It just takes a few lines of code (requires System.Windows namespace):

MyDataGrid.SelectAllCells();
ApplicationCommands.Copy.Execute(null, MyDataGrid);
MyDataGrid.UnselectAllCells(null, MyDataGrid);
var gridData = Clipboard.GetData(System.Windows.DataFormats.Text);

Use ‘CommaSeparatedValue’ DataFormat if plain text data doesn’t make sense.
To get all the data including headers, set the ClipboardCopyMode of your DataGrid to ‘IncludeHeader’.

You’re done. Easy, wasn’t it? ;)

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>