0

I am trying to do a foreach loop that stores each row from datatable1 into datatable2, so foreach row in datatable1 store the row in datatable2, this is what I have so far:

public static DataTable datatable2 = new DataTable();

public void createDatatable()
{
    profile p = new profile();
    DataTable datatable1 = p.getResults(System.Convert.ToInt32(HttpContext.Current.Session["ID"]));

    foreach (DataRow dr in datatable1.Rows)
    {
        datatable2 = datatable1.Copy();
    }
}

This just copies the columns too which I don't want, I just want each row stored from datatable2 into datatable1

Marc
  • 3,905
  • 4
  • 21
  • 37
c0mrade
  • 87
  • 9
  • 3
    possible duplicate of [copy rows from Datatable to another Datatable c#](http://stackoverflow.com/questions/4020270/copy-rows-from-datatable-to-another-datatable-c-sharp) – brendan Apr 28 '15 at 20:50
  • 2
    FYI, DataTable.Copy does not need to gon in that loop. The loop is actually just Copying the entire Datatable over and over. – Sully Apr 28 '15 at 20:57
  • @brendan That does not work, the foreach loop displays it multiple times according to how many rows you have. I have 3 rows, and now my datatable has 3x of the same rows because of the foreach – c0mrade Apr 28 '15 at 21:40

1 Answers1

0

I assume dataTable1 & dataTable2 has same schema (same number of columns with similar datatype). Don't use .Copy(). Use Rows.Add to copy content as follows,

foreach (DataRow dr in dataTable1.Rows) {
        dataTable2.Rows.Add(dr.ItemArray);
}
Abhishek
  • 6,912
  • 14
  • 59
  • 85