Vb.net – How to copy One row to another row in gridview

datagridviewvb.netwinforms

Using VB.Net

I want to Copy one row data to another row.

I am using checkbox in the gridview, if i clicked the checkbox and press button then selected row copy to new cell (row)

Below code is working for delete, not working for copy the rows

Code

 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

The above code is showing error as "Row provided already belongs to a DataGridView control."

What wrong with my code.

Need VB.Net Code Help

Best Answer

You can't add exactly the same row again. You will need to create a new row and populate it with the values from the row you are duplicating instead, then add the new row to the grvList.Rows

I am not sure what sorts of values you have in each cell, but as long as they are value types something like the following should work:

    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

Keep in mind that if the items in any of the cells are reference types that you will still be referencing the same item, instead of creating a copy of the item. Much as you were doing by simply calling add on the same row you located.

Sorry, I missed that the rows were DataGridView rows, rather than a datatable that was bound... this should do the trick in that case:

            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
Related Topic