如何将一行复制到gridview中的另一行

时间:2011-10-13 07:25:48

标签: vb.net winforms datagridview

使用VB.Net

我想将一行数据复制到另一行。

我在gridview中使用复选框,如果我单击复选框并按下按钮然后选择行复制到新单元格(行)

以下代码适用于删除,不适用于复制行

代码

 Private Sub btncopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncopy.Click
        For Each m_row As System.Windows.Forms.DataGridViewRow In Me.grvList.Rows
            If m_row.Cells("chksel").Value = True Then
               Me.grvList.Rows.Add(m_row)
             '  Me.grvList.Rows.Remove(m_row)
            End If
        Next
    End Sub

上面的代码显示错误为“提供的行已经属于DataGridView控件。”

我的代码有什么问题。

需要VB.Net代码帮助

2 个答案:

答案 0 :(得分:2)

您无法再次添加完全相同的行。您需要创建一个新行并使用您要复制的行中的值填充它,然后将新行添加到grvList.Rows

我不确定你在每个单元格中有什么样的值,但只要它们是值类型,就像下面这样的东西应该有效:

    For Each m_row As System.Windows.Forms.DataGridViewRow In Me.grvList.Rows
        If m_row.Cells("chksel").Value = True Then
            'Create new row to hold duplicated values
            Dim NewRow As DataRow = grvList.NewRow()
            'loop thru existing rows to copy values
            For i As Integer = 0 To m_row.Cells.Count - 1
                NewRow(i) = m_row.Cells(i).Value
            Next
            'Add newly create row to table
            Me.grvList.Rows.Add(NewRow)
            '  Me.grvList.Rows.Remove(m_row)
        End If
    Next

请记住,如果任何单元格中的项目都是引用类型,您仍将引用相同的项目,而不是创建项目的副本。就像你通过简单地在你找到的同一行上调用add一样。

抱歉,我错过了行是DataGridView行,而不是绑定的数据表......在这种情况下,这应该可以解决问题:

            For Each m_row As System.Windows.Forms.DataGridViewRow In Me.grvList.Rows
                If m_row.Cells("chksel").Value = True Then
                    'Create new row to hold duplicated values
                     Dim NewRow As DataGridViewRow = m_row.Clone
                     'Add newly create row to table
                     Me.grvLIst.Rows.Add(NewRow)
                End If
            Next

答案 1 :(得分:1)

'To copy Row
Private Sub CopyButton_Click(sender As System.Object, e As System.EventArgs) Handles CopyButton.Click
    CopyRowIndex = DGV1.CurrentRow.Index
End Sub

'To Paste Row
Private Sub PasteButton_Click(sender As System.Object, e As System.EventArgs) Handles PasteButton.Click
    PasteRowIndex = DGV1.CurrentRow.Index
    For index As Int32 = 0 To DGV1.ColumnCount - 1
        DGV1.Rows(CInt(PasteRowIndex)).Cells(index).Value = DGV1.Rows(CInt(CopyRowIndex)).Cells(index).Value
    Next

End Sub

'To Duplicate Rows
Private Sub DuplicateButton_Click(sender As System.Object, e As System.EventArgs) Handles DuplicateButton.Click
    CopyRowIndex = DGV1.CurrentRow.Index
    DGV1.Rows.Add()
    DuplicateRowIndex = DGV1.Rows.Count - 1
    For index As Int32 = 0 To DGV1.ColumnCount - 1
        DGV1.Rows(CInt(DuplicateRowIndex)).Cells(index).Value = DGV1.Rows(CInt(CopyRowIndex)).Cells(index).Value
    Next
End Sub