m ali
m ali

Reputation: 646

loop to add data from a different datatable

My DataTable which I want to call to my 2nd table:

First table:

 Dim table As New DataTable

 ' columns in the DataTable.
 table.Columns.Add("Monday", System.Type.GetType("System.Int32"))
 table.Columns.Add("Tuesday", System.Type.GetType("System.Int32"))
 table.Columns.Add("Wednesday", System.Type.GetType("System.Int32"))
 table.Columns.Add("Thursday", System.Type.GetType("System.Int32"))
 table.Columns.Add("Friday", System.Type.GetType("System.Int32"))
 '  rows with those columns filled in the DataTable.
 table.Rows.Add(1, 2005, 2000, 4000, 34)
 table.Rows.Add(2, 3024, 2343, 2342, 12)
 table.Rows.Add(3, 2320, 9890, 1278, 2)

now this is my 2nd table which i need to loop:

** not finished, want to add 1 from table to table2, in the first row.**

   Dim table2 As New DataTable


    ' columns in the DataTable.
    table2.Columns.Add("one", System.Type.GetType("System.String"))
    table2.Columns.Add("two", System.Type.GetType("System.String"))

    table2.Rows.Add()  *** add 1 (from monday) from first table**** ??
    table2.Rows.Add()
    table2.Rows.Add()
    table2.Rows.Add()

Using the table2, how can i link the information of Monday, to add in one in table 2, i will need a loop i think to call it.

In the first table, i want 1 that is in monday to show in "one" which is in the 2nd table, table2.

For alex:

 Monday    Tuesday    Wed
 10           40       9
 20           50       6
 30           70       4

Upvotes: 1

Views: 4660

Answers (1)

Alex
Alex

Reputation: 4948

Here is how to add the first column value of Table1 to your Table2

For Each row As DataRow In table.Rows
    table2.Rows.Add(row(0)) 'This will add the first column value of Table1 to the first column of Table2

    'Here's how the index works:
    'table.Rows.Add(1, 2005, 2000, 4000, 34)
    'row(0) = 1
    'row(1) = 2005
    'row(2) = 2000
    'row(3) = 4000
    'row(4) = 34
Next

To add values to your two columns in Table2 you would do this:

For Each row As DataRow In table.Rows
    table2.Rows.Add({row(0), row(1)})

    'If I take your second example:
     Monday    Tuesday    Wed
     10           40       9
     20           50       6
     30           70       4

    'The first iteration through Table1 will add (10,40)
    'The second iteration through Table1 will add (20,50)
    'And so on...
Next

Upvotes: 4

Related Questions