2

I want to copy all rows in old datatable (oldDT) to a new datatable (dt) using ImportRow method. But the new row doesn't have a same column with the old one. Here is my code:

foreach (DataRow dr in oldDT.Rows)
{
    MessageBox.Show(dr["tenant_no"].ToString()); //giving a correct result
    dt.ImportRow(dr);
    MessageBox.Show(dt.Rows[0]["tenant_no"].ToString()); //giving an error Column 'tenant_no' does not belong to table .
}

i try to use the answer C# simple way to copy or clone a DataRow? and here is my new code:

foreach (DataRow dr in oldDT.Rows)
{
    MessageBox.Show(dr["tenant_no"].ToString());
    DataRow newDR = oldDT.NewRow();
    newDR.ItemArray = dr.ItemArray.Clone() as object[];
    dt.Rows.Add(newDR); //giving an error "This row already belongs to another table."
    MessageBox.Show(dt.Rows[0]["tenant_no"].ToString());
}

Anyone can help me?

Community
  • 1
  • 1
Kuro13
  • 105
  • 1
  • 9

2 Answers2

1

You could use DataTable.Copy, if you are not locked into using the ImportRow :

Copies both the structure and data for this DataTable.

DataTable dt = oldDt.Copy();
DROP TABLE users
  • 1,955
  • 14
  • 26
  • actually, i want to join more than 1 old table into one. so i think this can't be used. – Kuro13 Dec 24 '13 at 03:33
  • @Kuro13 Ok, sorry didn't know that. Does it work if you just use `NewDataTable.Rows.Add(drfromoldtable);` ? – DROP TABLE users Dec 24 '13 at 03:35
  • it will giving an error "row is already belong to another table" because as far as i know, a row can only belong to 1 table. – Kuro13 Dec 24 '13 at 03:38
  • @Kuro13 ah yes that pesky error. Maybe this answer could help you, if you have not tried this already. http://stackoverflow.com/a/12025072/1483002 – DROP TABLE users Dec 24 '13 at 03:41
  • finally i use 'datatable.clone()' to clone just the schema and it works. thanks.. – Kuro13 Dec 24 '13 at 04:23
1

Try this... this will work

 DataTable dt= new DataTable();
   dt= oldDT.Clone();
    for (int i=0;i < oldDT.Rows.Count; i++)
    {
        dt.ImportRow(dataTable.Rows[i]);
    }
Kumod Singh
  • 2,113
  • 1
  • 16
  • 18