본문 바로가기
VB.net/DataGridView

데이터그리드뷰 복사하기

by 호야호잇 2018. 10. 22.
'References to source and target grid.

Dim sourceGrid As DataGridView = Me.DataGridView1
Dim targetGrid As DataGridView = Me.DataGridView2

'Copy all rows and cells.

Dim targetRows = New List(Of DataGridViewRow)

For Each sourceRow As DataGridViewRow In sourceGrid.Rows

    If (Not sourceRow.IsNewRow) Then

        Dim targetRow = CType(sourceRow.Clone(), DataGridViewRow)

        'The Clone method do not copy the cell values so we must do this manually.
        'See: https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.clone(v=vs.110).aspx

        For Each cell As DataGridViewCell In sourceRow.Cells
            targetRow.Cells(cell.ColumnIndex).Value = cell.Value
        Next

        targetRows.Add(targetRow)

    End If

Next

'Clear target columns and then clone all source columns.

targetGrid.Columns.Clear()

For Each column As DataGridViewColumn In sourceGrid.Columns
    targetGrid.Columns.Add(CType(column.Clone(), DataGridViewColumn))
Next

'It's recommended to use the AddRange method (if available)
'when adding multiple items to a collection.

targetGrid.Rows.AddRange(targetRows.ToArray())