我有两个数据表如何将目标行索引复制到同一索引中的另一个数据表中,请检查下面的代码。
Dim datatable1 As DataTable = GetEmployeeSummary()
Dim datatable2 As DataTable = GetEmployees()
For i As Integer = 0 To datatable1.Rows.Count - 1 'Datatable1.rows.count = datatable2.rows.count
Select Case i
Case 1, 5, 6, 19, 24
datatable2.Rows(i) = datatable2.Rows(i) 'how i could copy targeted rows index to another datatable in the same index
End Select
Next
答案 0 :(得分:4)
如果两个表具有相同的列,则可以使用DataRow.ItemArray
:
For i As Int32 = 0 To datatable1.Rows.Count - 1
Select Case i
Case 1, 5, 6, 19, 24
If datatable2.Rows.Count - 1 >= i Then
datatable2.Rows(i).ItemArray = datatable1(i).ItemArray
Else
Dim row = datatable2.Rows.Add()
row.ItemArray = datatable1(i).ItemArray
End If
End Select
Next
答案 1 :(得分:1)
我建议使用ImportRow
。它会将整行复制到您的DataTable中。所以你的代码就像下面一样。
Dim datatable1 As DataTable = GetEmployeeSummary()
Dim datatable2 As DataTable = GetEmployees()
For i As Integer = 0 To datatable1.Rows.Count - 1
Select Case i
Case 1, 5, 6, 19, 24
datatable2.ImportRow(datatable2.Rows(i))
End Select
Next