如何将一个DataGridview中的内容复制到另一种格式的
For i As Integer = DataGridView1.Rows.Count - 1 To 0 Step -1
With DataGridView1.Rows(i)
DataGridView2.Rows.Insert(0, .Cells(0).Value, .Cells(1).Value, .Cells(2).Value, .Cells(3).Value)
End With
Next
答案 0 :(得分:0)
请参阅this answer,其中已经介绍了从一个DataGridView复制到另一个。
我获取了代码,并使用an online converter转换为vb.net。
要使此代码正常工作,请创建一个具有两个表单(Form1,Form2)的新项目,每个表单上都带有一个DataGridView(均名为DataGridView1)。将一个按钮放在Form1(Button1)上。然后将代码粘贴到每个表单的相应代码文件中。
Form1
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.DataSource = {"A", "B", "C"}.Select(Function(s) New With {.Value = s}).ToList()
Form2.Show()
End Sub
Public Sub Foo()
Form2.Bar(DataGridView1)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Foo()
End Sub
End Class
Form2
Public Class Form2
Public Sub Bar(dgv_org As DataGridView)
Dim dgv_copy = DataGridView1
Try
If dgv_copy.Columns.Count = 0 Then
For Each dgvc As DataGridViewColumn In dgv_org.Columns
dgv_copy.Columns.Add(TryCast(dgvc.Clone(), DataGridViewColumn))
Next
End If
Dim row As DataGridViewRow = New DataGridViewRow()
For i As Integer = 0 To dgv_org.Rows.Count - 1
row = CType(dgv_org.Rows(i).Clone(), DataGridViewRow)
Dim intColIndex As Integer = 0
For Each cell As DataGridViewCell In dgv_org.Rows(i).Cells
row.Cells(intColIndex).Value = cell.Value
intColIndex += 1
Next
dgv_copy.Rows.Add(row)
Next
dgv_copy.AllowUserToAddRows = False
dgv_copy.Refresh()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class