How to copy One row to another row in gridview

前端 未结 2 1742
逝去的感伤
逝去的感伤 2021-01-27 06:23

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 t

2条回答
  •  闹比i
    闹比i (楼主)
    2021-01-27 06:48

    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
    

提交回复
热议问题