Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy rows between two datatable VB.net

I have two datatable how i could copy targeted rows index to another datatable in the same index, Please check below code.

            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
like image 323
KaZzA Avatar asked Sep 01 '25 03:09

KaZzA


2 Answers

You can use the DataRow.ItemArray if both tables have the same columns:

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
like image 138
Tim Schmelter Avatar answered Sep 04 '25 06:09

Tim Schmelter


I recommend of using ImportRow. It will copy the whole row into your DataTable. So Your code would be like below.

    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
like image 25
Menuka Ishan Avatar answered Sep 04 '25 07:09

Menuka Ishan