Copy Selected DataGridView Cells to Clipboard

To copy selected cells to the Clipboard without Column Headers:

If dg.GetClipboardContent Is Nothing Then

MessageBox.Show(“Nothing selected to copy to clipboard.”)

Else

Me.dg.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText

Clipboard.SetDataObject(Me.dg.GetClipboardContent)

End If

 

To copy selected cells to the Clipboard with Column Headers requires a bit more work because there is a leading tab/column that needs to be removed:

If dg.GetClipboardContent Is Nothing Then

MessageBox.Show(“Nothing selected to copy to clipboard.”)

Else

Me.dg.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText

Dim clipData As String = dg.GetClipboardContent.GetText()

Dim lines As String() = Regex.Split(clipData, “rn”)

Dim newClipData As New StringBuilder

Dim tab As Char = vbTab

For Each line As String In lines

newClipData.Append(line.Substring(line.IndexOf(tab) + 1) + vbCrLf)

Next

Clipboard.SetText(newClipData.ToString(), TextDataFormat.Text)

End If