65.9K
CodeProject is changing. Read more.
Home

Copying DataGridView Contents To Clipboard

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Nov 9, 2012

CPOL
viewsIcon

49497

Copy DataGridView contents to clipboard regardless of current selection.

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    'Get header
    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    'Get rows
    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    'Put to clipboard
    Dim o As New DataObject
    o.SetText(s)
    Clipboard.SetDataObject(o, True)
End Sub