vb.net - 如何将整列从一个数据 GridView 复制到另一个数据 GridView ?

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

enter image description here

有两个 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

最佳答案

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

替换

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

关于vb.net - 如何将整列从一个数据 GridView 复制到另一个数据 GridView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30044019/

相关文章:

vb.net - Gridview 显示和隐藏特定列

regex - 6位正则表达式

javascript - 显示加载进度模式不隐藏

iphone - if 语句的问题 ||

c++ - for循环的增量语句中的奇数位运算符

vb.net - 进行绑定(bind)组合框选择时 Windows 窗体卡住

java - 如何扫描用户输入并在关键字匹配时打印字符串?

ios - “永远不会被执行”

python - 遍历 python 中的 numpy 数组行

由于循环,Swift 完成处理程序 For 循环将执行一次而不是 10 次