【问题标题】:How to copy whole column from one datagridview to another?如何将整列从一个datagridview复制到另一个?
【发布时间】:2015-05-03 08:50:35
【问题描述】:

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

复选框是 dgvReport 中列的名称。例如,如果用户选择“电子邮件”,则应将“电子邮件”的列及其行数据添加到 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

【问题讨论】:

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


    【解决方案1】:

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

    替换

    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
    

    以下内容:

            If dgvReport2.Rows.Count > 0 Then
                For rows As Integer = 0 To dgvReport.Rows.Count - 1
                    dgvReport2.Rows(rows).Cells(newCol).Value =
                    dgvReport.Rows(rows).Cells(1).Value
                Next
            Else
                For rows As Integer = 0 To dgvReport.Rows.Count - 1
                    dgvReport2.Rows.Add(dgvReport.Rows(rows).Cells(1).Value)
                Next
            End If
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多