如何将整列从一个datagridview复制到另一个?

时间:2015-05-03 08:50:36

标签: vb.net if-statement for-loop datagridview copy

enter image description here

有两个datagridview(dgvReport和dgvReport2)。 dgvReport在选择字段后显示来自服务器的数据(工作正常)。

复选框是dgvReport中列的名称。如果用户选择"电子邮件"例如" Email"的列及其行数据。应该添加到dgvReport2。

我的问题是,当我选择多个复选框时,行的输出仅显示在dgvReport2的第一列,而不是在相应的列下。例如,在屏幕截图中的列" fname"数据显示在dgvReport2的电子邮件列下。

如何将行数据放在适当的列下?

以下是我的编码:

'Add dynamic column
Dim newCol As Integer = 0

If chkEmail.Checked = True Then
    Dim column As New DataGridViewTextBoxColumn
    dgvReport2.Columns.Insert(newCol, column)

    With column
        .HeaderText = "email"
        .AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
        .ReadOnly = True
    End With

    For rows As Integer = 0 To dgvReport.Rows.Count - 1
        For colcnt As Integer = 0 To dgvReport.Columns.Count - 17
            dgvReport2.Rows.Add(dgvReport.Rows(rows).Cells(0).Value)
        Next
    Next

    newCol += 1
End If

If chkFname.Checked = True Then
    Dim column As New DataGridViewTextBoxColumn
    dgvReport2.Columns.Insert(newCol, column)

    With column
        .HeaderText = "fname"
        .AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
        .ReadOnly = True
    End With

    For rows As Integer = 0 To dgvReport.Rows.Count - 1
        For colcnt As Integer = 0 To dgvReport.Columns.Count - 17
            dgvReport2.Rows.Add(dgvReport.Rows(rows).Cells(1).Value)
        Next
    Next
    newCol += 1
End If

1 个答案:

答案 0 :(得分:0)

我找到了自己问题的答案。希望能够帮助其他正在寻找相同问题的人:

替换

+

以下内容:

For rows As Integer = 0 To dgvReport.Rows.Count - 1
  For colcnt As Integer = 0 To dgvReport.Columns.Count - 17
    dgvReport2.Rows.Add(dgvReport.Rows(rows).Cells(0).Value)
  Next
Next