我想使用以下代码将行从DataGridViewX1
移到另一个表单的DataGridView
:
按钮点击事件:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
frmEncodeDatabase.EncodingCompleteDataGridView.DataSource = DataGridViewX1.Rows
frmEncodeDatabase.Show()
End Sub
另一种形式DataGridView
的{{1}}事件:
RowsAdd
现在上面的代码是我遇到问题的地方:StackOverflowException。 (错误的描述如下图所示)
答案 0 :(得分:0)
这是一个帮助您朝着正确方向前进的通用示例。
这个例子:
我意识到你的真实生活示例在不同的表单上有datagridviews,但是对于这个例子,代码在一个表单上更容易理解。
要测试此操作,请执行以下操作:
1)创建一个新表单(Form1),添加2个datagridviews(DataGridView1和DataGridView2)和一个按钮(Button1)
2)将Form1上的代码替换为:
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
答案 1 :(得分:0)
Dim dt As DataTable = CType(DataGridView1.DataSource, DataTable)
DataGridView2.DataSource = dt.Copy()
它允许我将内容从dgv1复制到dgv2。