Here is a generic example to help you in the right direction.
This example:
- Demonstrates how to combine rows from a datagridview that is not databound into a datagridview that is databound
- Assumes that both datagridviews have the same number of columns and in the same order.
- Assumes that the databound gridview is bound to a datatable.
I realize your real life example has the datagridviews on separate forms but the code is easier to follow on one form for this example.
To test this, do the following:
1) Create a new form (Form1), add 2 datagridviews (DataGridView1 and DataGridView2) and one button (Button1)
2) Replace the code on Form1 one with this:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Manually add columns to the first datagridview which will not be data bound
Me.DataGridView1.Columns.Add("Column1", "Column1")
Me.DataGridView1.Columns.Add("Column2", "Column2")
Me.DataGridView1.Columns.Add("Column3", "Column3")
' Poulate both datagridviews
PopulateDataGrid1Manually()
PopulateDataGrid2DataBound()
End Sub
Private Sub PopulateDataGrid1Manually()
' This datagridview has data added manually without being databound
Dim sRow(Me.DataGridView1.ColumnCount - 1) As String
For r As Int32 = 1 To 3 ' Adding 3 rows of test data
For c As Int32 = 0 To Me.DataGridView1.ColumnCount - 1
sRow(c) = "data" & r.ToString
Next
Me.DataGridView1.Rows.Add(sRow)
Next
End Sub
Private Sub PopulateDataGrid2DataBound()
' This datagridview is databound to a datatable
Dim dt As New DataTable
dt.Columns.Add("Column1", GetType(String))
dt.Columns.Add("Column2", GetType(String))
dt.Columns.Add("Column3", GetType(String))
Dim dr As DataRow
For i As Int32 = 1 To 3 ' Adding 3 rows of test data
dr = dt.NewRow
dr("Column1") = "new" & i.ToString
dr("Column2") = "new" & i.ToString
dr("Column3") = "new" & i.ToString
dt.Rows.Add(dr)
Next
Me.DataGridView2.DataSource = dt ' Databind
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Copy rows from the first datagridview to the second datagridview that is data bound
' First copy the second datagridviews datasource into a new data table
Dim dt As DataTable = CType(Me.DataGridView2.DataSource, DataTable).Copy
Dim dr As DataRow
' Loop through all rows of the first datagridview and copy them into the data table
For r As Int32 = 0 To Me.DataGridView1.Rows.Count - 1
If Me.DataGridView1.Rows(r).IsNewRow = False Then ' Do not copy the new row
dr = dt.NewRow
' Loop through all cells of the first datagridview and populate the data row
For c As Int32 = 0 To Me.DataGridView1.ColumnCount - 1
dr(c) = Me.DataGridView1.Rows(r).Cells(c).Value
Next
dt.Rows.Add(dr) ' Add the data row to the data table
End If
Next
Me.DataGridView2.DataSource = dt ' Rebind the second datagridview with the new table which has all the rows from both datagridviews
End Sub
End Class
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…