如何将一个DataGridview中的内容复制到另一个DataGridview

Rom*_*man 0 vb.net datagridview

我想从一个datagridview复制到另一个datagridview。

我尝试了下面的代码,但第一列中仍然有所有数据:

For c = 0 To ReadDataDataGridView.Rows.Count - 1
    For t = 0 To ReadDataDataGridView.Columns.Count - 1
        DataGridView1.Rows.Add(ReadDataDataGridView.Rows(c).Cells(t).Value)
    Next
Next
Run Code Online (Sandbox Code Playgroud)

Bjø*_*sjå 5

问题是您要为中的每个单元格添加一个新行ReadDataDataGridView。您只需要创建一个在每一行迭代行。到目前为止,您将n在每次行迭代中创建行(其中n是列数)。

这是一种实现方法:

VB.NET

'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())
Run Code Online (Sandbox Code Playgroud)

C#

//References to source and target grid.

DataGridView sourceGrid = this.dataGridView1;
DataGridView targetGrid = this.dataGridView2;

//Copy all rows and cells.

var targetRows = new List<DataGridViewRow>();

foreach (DataGridViewRow sourceRow in sourceGrid.Rows)
{

    if (!sourceRow.IsNewRow)
    {

        var targetRow = (DataGridViewRow)sourceRow.Clone();

        //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

        foreach (DataGridViewCell cell in sourceRow.Cells)
        {
            targetRow.Cells[cell.ColumnIndex].Value = cell.Value;
        }

        targetRows.Add(targetRow);

    }

}

//Clear target columns and then clone all source columns.

targetGrid.Columns.Clear();

foreach (DataGridViewColumn column in sourceGrid.Columns)
{
    targetGrid.Columns.Add((DataGridViewColumn)column.Clone());
}

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

targetGrid.Rows.AddRange(targetRows.ToArray());
Run Code Online (Sandbox Code Playgroud)