簡體   English   中英

在 DataGridView 中復制/粘貼

[英]Copy/Paste within DataGridView

我正在嘗試在 DataGridView 中進行復制和粘貼,以類似於 Excel。 我當前的代碼執行此操作,但第一個單元格除外,它似乎將剪貼板中的所有內容粘貼到第一個單元格中。 下面是我在cell_keydown事件中使用的代碼。

澄清一下,如果我復制以下內容:

復制數據

我得到結果:

粘貼的數據

在單擊單元格之前,粘貼的數據在兩個日期之間確實有一個空格。

如果有人有更好的方法來完成我最終想要做的事情,那也將不勝感激!

If e.Control AndAlso e.KeyCode = Keys.C Then
    Dim d As DataObject = dgv1.GetClipboardContent()
    Clipboard.SetDataObject(d)
    e.Handled = True

ElseIf e.Control AndAlso e.KeyCode = Keys.V Then
    Dim s As String = Clipboard.GetText().Replace(vbCr, " ")
    Dim lines As String() = s.Trim.Split(vbLf)
    Dim row As Integer = dgv1.CurrentCell.RowIndex
    Dim col As Integer = dgv1.CurrentCell.ColumnIndex
    Dim linesCount As Integer = lines.Count()

    If (row + linesCount) - dgv1.RowCount > 0 Then dgv1.Rows.Add((row + linesCount) - dgv1.RowCount)

    For Each line As String In lines
        If line.Length > 0 Then
            Dim cells As String() = line.Split(vbTab)
            For i As Integer = 0 To cells.GetLength(0) - 1
                dgv1.CurrentCell.Value = cells(i)
                If col + i < dgv1.ColumnCount Then
                    dgv1(col + i, row).Value = cells(i)
                Else
                    Exit For
                End If
            Next
            row += 1
        Else
            Exit For
        End If
    Next
End If

最好為復制/粘貼例程創建方法,這樣您就可以從代碼中的不同位置調用它們,例如在按鈕單擊時、在按鍵時、在菜單項單擊時……等等。

我認為您對Copy部分沒有問題,因為GetClipboardContent function 可以完成這項工作。 至於Paste部分,以下代碼片段從剪貼板中獲取數據,並粘貼從 CurrentCell 開始的單元格選擇范圍的值。 超出范圍的單元格被修剪。

Private Sub CopyCells()
    Clipboard.SetDataObject(DataGridView1.GetClipboardContent)
End Sub

Private Sub PasteCells()
    Dim s = Clipboard.GetText
    Dim ci = DataGridView1.CurrentCell.ColumnIndex
    Dim ri = DataGridView1.CurrentCell.RowIndex
    Dim colCount = DataGridView1.Columns.Count
    Dim rowCount = DataGridView1.Rows.Count

    For Each r In s.Split({ControlChars.CrLf}, StringSplitOptions.None)
        Dim Cell = ci
        For Each c In r.Split({ControlChars.Tab}, StringSplitOptions.None)
            If Cell >= colCount Then Exit For
            DataGridView1(Cell, ri).Value = c
            Cell += 1
        Next
        ri += 1
        If ri >= rowCount Then Exit For
    Next
End Sub

從 DGV.KeyDown 事件中調用它們,例如如下:

Private Sub DataGridView1_KeyDown(sender As Object, e As KeyEventArgs) Handles DataGridView1.KeyDown
    If e.Control Then
        Select Case e.KeyCode
            Case Keys.C
                CopyCells()
                e.Handled = True
            Case Keys.V
                PasteCells()
                e.Handled = True
        End Select
    End If
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM