0

How to loop though datatable and save result in different datatable

I am using vb asp.net

Below I have 2 datatables and results

Dim NewDtatTable1 As DataTable = getResults()
Dim NewDtatTable2 As DataTable = NewDtatTable1 

NewDtatTable1 Result:

|------------|--------|--------|
| myLocation | myName | date   |
|------------|--------|--------|
| New york   | name1  | 1/1/12 |
| Boston     | name2  | 1/1/13 |
| New york   | name3  | 1/1/14 |
| New york   | name4  | 1/1/15 |
| Boston     | name5  | 1/1/16 |
|------------|--------|--------|

i want to loop though datatable name NewDtatTable1 and if myLocation is equal to 'new york' than i want to add that row to new datatable NewDtatTable2

For Each row As DataRow In NewDtatTable21.Rows
        If (String.Compare(row.Item("myLocation").ToUpper(), "NEW YORK", True) = 0) 
        Dim R As DataRow = NewDtatTable21.NewRow
        NewDtatTable.Rows.Add(NewDtatTable1 .Rows.Item(row))
    End If
End If

I want NewDtatTable2 result to be this:

|------------|--------|--------|
| myLocation | myName | date   |
|------------|--------|--------|
| New york   | name1  | 1/1/12 |
| New york   | name3  | 1/1/14 |
| New york   | name4  | 1/1/15 |
|------------|--------|--------|
braX
  • 11,506
  • 5
  • 20
  • 33
  • [link](https://stackoverflow.com/questions/4020270/copy-rows-from-one-datatable-to-another-datatable) – Tamás Kecskeméti Jan 26 '18 at 19:13
  • Possible duplicate of [Copy rows from one Datatable to another DataTable?](https://stackoverflow.com/questions/4020270/copy-rows-from-one-datatable-to-another-datatable) – Peter Jan 26 '18 at 20:20

1 Answers1

0

You are setting NewDtatTable2 = NewDtatTable1 instead of cloning the structure of the table. So you could do something like this to copy the row values instead of copying row references.

Dim NewDtatTable1 As DataTable = getResults()
Dim NewDtatTable2 As DataTable = NewDtatTable1.Clone()

For Each row As DataRow In NewDtatTable1.Rows
    If (String.Equals(row.Item("myLocation"), "New York", StringComparison.CurrentCultureIgnoreCase)) 
        NewDtatTable2.Rows.Add(row.ItemArray)
    End If
End For
npearson
  • 692
  • 4
  • 17