0

我想将剪贴板中的数据粘贴到 DGV 中的选定单元格。我找到了以下链接:https ://www.codeproject.com/Articles/208281/Copy-Paste-in-Datagridview-Control但我对 C# 一无所知,所以我使用在线工具将代码转换为 VB.net。复制和剪切部分正在工作,但我无法粘贴到 DGV。代码如下所示:

 'paste data
Private Sub PasteToolStripMenuItem1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles PasteToolStripMenuItem1.Click
    PasteClipboardToDGV()
End Sub

Private Sub PasteClipboardToDGV()
    If DgvLeidingen.SelectedCells.Count = 0 Then
        MessageBox.Show("Please select a cell", "Paste", MessageBoxButtons.OK, MessageBoxIcon.Warning)

        Return
    End If

    Dim startCell As DataGridViewCell = GetStartCell(DgvLeidingen)
    Dim cbValue As Dictionary(Of Integer, Dictionary(Of Integer, String)) = ClipBoardValues(Clipboard.GetText())
    Dim iRowIndex As Integer = startCell.RowIndex

    For Each rowKey As Integer In cbValue.Keys

        Dim iColIndex As Integer = startCell.ColumnIndex

        For Each cellKey As Integer In cbValue(rowKey).Keys
            If iColIndex <= DgvLeidingen.Columns.Count - 1 AndAlso iRowIndex <= DgvLeidingen.Rows.Count - 1 Then
                Dim cell As DataGridViewCell = DgvLeidingen(iColIndex, iRowIndex)

            End If

            iColIndex = iColIndex + 1
        Next
        iRowIndex = iRowIndex + 1
    Next
End Sub

Private Function GetStartCell(ByVal DGV As DataGridView) As DataGridViewCell
    If DGV.SelectedCells.Count = 0 Then Return Nothing

    Dim rowIndex As Integer = DGV.Rows.Count - 1
    Dim colIndex As Integer = DGV.ColumnCount -1

    For Each dgvCell As DataGridViewCell In DGV.SelectedCells
        If dgvCell.RowIndex < rowIndex Then rowIndex = dgvCell.RowIndex
        If dgvCell.ColumnIndex < colIndex Then colIndex = dgvCell.ColumnIndex
    Next

    Return DGV(colIndex, rowIndex)

End Function

Private Function ClipBoardValues(ByVal clipboardValue As String) As Dictionary(Of Integer, Dictionary(Of Integer, String))

    Dim copyValues As Dictionary(Of Integer, Dictionary(Of Integer, String)) = New Dictionary(Of Integer, Dictionary(Of Integer, String))()
    Dim lines As String() = clipboardValue.Split(vbLf)

    For i As Integer = 0 To lines.Length - 1
        copyValues(i) = New Dictionary(Of Integer, String)()
        Dim lineContent As String() = lines(i).Split(vbTab)
        If lineContent.Length = 0 Then
            copyValues(i)(0) = String.Empty
        Else
            For j As Integer = 0 To lineContent.Length - 1


                copyValues(i)(j) = lineContent(j)
            Next
        End If
    Next

    Return copyValues

End Function
4

1 回答 1

0

在vb代码中,需要在“Dim cell As DataGridViewCell = DgvLeidingen(iColIndex, iRowIndex)”之后放置“If cell.Selected Then cell.Value = cbValue(rowKey)(cellKey)”

于 2022-01-05T23:22:30.550 回答