Click here to Skip to main content
Click here to Skip to main content
Go to top

Copying DataGridView Contents To Clipboard

, 9 Nov 2012
Rate this:
Please Sign up or sign in to vote.
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

miteleda

Australia Australia
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 9 Nov 2012
Article Copyright 2012 by miteleda
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid