将 DataGridView 内容复制到剪贴板
无论当前选择如何,将 DataGridView 内容复制到剪贴板。
介绍
此代码片段将 DataGridView
的整个内容复制到剪贴板,包括标题,尊重显示的列顺序并排除不可见列 - 最重要的是 - 无论网格中当前选择什么内容。
背景
DataGridView
允许您使用其 GetClipboardContent
方法将网格中选择的内容复制到剪贴板。我需要提供一种复制整个网格内容而不考虑所选内容的方法。这段代码非常简单,但我花了太长时间才找到它,没有成功,所以我想把它发布出来,以节省下一个人的时间。
使用代码
将以下方法添加到您的代码中,传入您的 DataGridView 引用即可。
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