datagridview getclipboardcontent paste has blank first row column
I have a app that is populating a datagridview and have a button to highlight and copy all the data in the datagridview. When I go and paste into excel the first row and first column are blank. Is there a easy switch to not include this?
Here is the code testing with.
Code:
Private Sub btnCopyAll_Click(sender As System.Object, e As System.EventArgs) Handles btnCopyAll.Click
Dim sClipboard As String = String.Empty
dgvResults.SelectAll()
dgvResults.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
If Me.dgvResults.GetCellCount(DataGridViewElementStates.Selected) > 0 Then
Try
' Add the selection to the clipboard.
Clipboard.SetDataObject(Me.dgvResults.GetClipboardContent())
' Replace the text box contents with the clipboard text.
sClipboard = sClipboard + vbCrLf + Clipboard.GetText()
Catch ex As System.Runtime.InteropServices.ExternalException
Throw New Exception(ex.Message, ex.InnerException)
MessageBox.Show("The Clipboard could not be accessed.", "Please try again.", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End If
Clipboard.SetText(sClipboard)
End Sub
Re: datagridview getclipboardcontent paste has blank first row column
Well you have to make some decisions. If you include headers then that means a space is also required for row headers, hence the spare column. The spare row is introduced by the procedure in which you first copy the data, read it back to a string and then copy the string, of which I really can't see any necessity anyway.
Re: datagridview getclipboardcontent paste has blank first row column
Thanks. That helped me figured it out.
1) I had a vbCrLf that was adding the space above the header. Removed that
2) I needed to set the RowHeaderVisible to false. I was only thinking column header but guess you have two headers.
Code:
Private Sub btnCopyAll_Click(sender As System.Object, e As System.EventArgs) Handles btnCopyAll.Click
Dim sClipboard As String = String.Empty
dgvResults.AutoResizeColumns()
dgvResults.RowHeadersVisible = False
dgvResults.SelectAll()
dgvResults.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
If Me.dgvResults.GetCellCount(DataGridViewElementStates.Selected) > 0 Then
Try
' Add the selection to the clipboard.
Clipboard.SetDataObject(Me.dgvResults.GetClipboardContent())
' Replace the text box contents with the clipboard text.
sClipboard = Clipboard.GetText()
Catch ex As System.Runtime.InteropServices.ExternalException
Throw New Exception(ex.Message, ex.InnerException)
MessageBox.Show("The Clipboard could not be accessed.", "Please try again.", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End If
Clipboard.SetText(sClipboard)
End Sub