Introduction
This code snippet copies the entire contents of a DataGridView
to clipboard, including headers, respecting the displayed column
order and excluding invisible columns - and most importantly - irrespective of what is currently selected in the grid.
Background
The DataGridView
allows you to copy what is selected in the grid to the clipboard using its GetClipboardContent
method. I needed to provide a means of copying
the entire grid's contents irrespective of what was selected. The code is quite simple but I spent too long trying to find it without success so thought I'd post
it to save the next person.
Using the code
Add the following method to your code, pass in the reference to your DataGridView and that's it.
Private Sub CopyDataGridViewToClipboard(ByRef dgv As DataGridView)
Dim s As String = ""
Dim oCurrentCol As DataGridViewColumn
oCurrentCol = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible)
Do
s &= oCurrentCol.HeaderText & Chr(Keys.Tab)
oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, _
DataGridViewElementStates.Visible, DataGridViewElementStates.None)
Loop Until oCurrentCol Is Nothing
s = s.Substring(0, s.Length - 1)
s &= Environment.NewLine
For Each row As DataGridViewRow In dgv.Rows
oCurrentCol = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible)
Do
If row.Cells(oCurrentCol.Index).Value IsNot Nothing Then
s &= row.Cells(oCurrentCol.Index).Value.ToString
End If
s &= Chr(Keys.Tab)
oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, _
DataGridViewElementStates.Visible, DataGridViewElementStates.None)
Loop Until oCurrentCol Is Nothing
s = s.Substring(0, s.Length - 1)
s &= Environment.NewLine
Next
Dim o As New DataObject
o.SetText(s)
Clipboard.SetDataObject(o, True)
End Sub