vb.net Datagrid到另一个datagrid的值

时间:2019-11-21 02:03:16

标签: vb.net datagridview

大家好,我在使用vb.net将datagrid值传递给另一个datagrid时遇到了问题。因为youtube上的大多数教程都在datagrid的行上固定了值。我希望在数据库中获取行的值,然后将其传递给Datagrid1,然后传递给单击按钮时Datagrid 2非常感谢

表单加载中的代码如下:

    Me.DataGridView1.columns.Add("1","1")

Me.DataGridView1.columns.Add("2","1")
Me.DataGridView1.columns.Add("3","3")
Me.DataGridView2.columns.Add("1","1")
Me.DataGridView2.columns.Add("2","1")

以及用于传递值的按钮上:

dim dr as  new System.Windows.Forms.datagridviewrow 
for each dr In me.datagridview1.selectedRows
  Me.DatagridView2.rows.Add(dr.cells(0).value,dr.cells(1).value,dr.cells(2).value....and so on)

1 个答案:

答案 0 :(得分:0)

    Dim sourceGrid As DataGridView = Me.DataGridView1
    Dim targetGrid As DataGridView = Me.DataGridView2
    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)
            For Each cell As DataGridViewCell In sourceRow.Cells
                targetRow.Cells(cell.ColumnIndex).Value = cell.Value
            Next
            targetRows.Add(targetRow)
        End If
    Next
    targetGrid.Columns.Clear()
    For Each column As DataGridViewColumn In sourceGrid.Columns
        targetGrid.Columns.Add(CType(column.Clone(), DataGridViewColumn))
    Next
    targetGrid.Rows.AddRange(targetRows.ToArray())