Copying Column Text Only from SL DataGrid

Normally while working on systems, it is quite habitual for all of us to use keyboard shortcuts rather than moving the hand away, holding the mouse, and click and dragging stuff. But then at times, that seems to be the easier option, especially when we need to be selecting options, rows selectively, i.e. choose on demand. Well, this blog is for the time when working from the keyboard seems to be easier, especially copy and paste options. While copying from a SilveriLight DataGrid, so many a times we need to select a row and paste it say in an Excel sheet, or even Notepad file for that matter, and we select the row, hit CTRL + C , switch to the required application using ALT + TAB, (atleast its convenient for me that ways ), and hit CTRL+V. But then what we see is not what we expected as, not just the row data but also the column headers get copied on to the output location. There is one more scenario that plays out, if you are somewhat observant. Suppose while designing the Grid you left a few columns hidden, and as expected they are not being displayed on the web page, but then when you copy and paste, the data from those columns is copied as well. This for the developer is not so annoying as is for the end user. And as a developer, I believe it would be our job to give the end user, only what they demand and not all that we have. :) So the following is one approach, to restrict the grid from showing all, and sending only displayed data to the clipboard. We handle the KeyDown event of the grid, check for the correct key combination that triggers the copy action, namely, CTRL + C. Once we get this the key combination, we search the SelectedCells, check for column visibility and then only allow data to be stored as a string, which is then passed on to the clipboard. Here is the code implementing the same, if (e.Key == Key.C && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) { string _data = ""; Clipboard.SetText(string.Empty); foreach (DataGridCell p in dg.Selection.SelectedCells ) { if(p.Column.Visibility==Visibility.Visible) _data = _data + " "+ p.Text; } Clipboard.SetText(_data); e.Handled = true; } The above code goes into the Grid_KeyDown(Object sender, KeyEventArgs e) event of the SLDataGrid. Also attached at the link below is a sample implementing the same. Download Sample


GrapeCity Developer Tools
comments powered by Disqus