0

The array is obtained by a linq query on a datatable. When I try to add it to another datatable it gives the exception that the row belongs to another table.

need to add the row to the top of the table not at the bottom

DataRow[] recovery_rows = Sub_DataTable.Select("ProductId = " + last_product_id.ToString() + ""); //Sub_DataTable is a datatable
for (int rev_row = 0; rev_row < recovery_rows.Count(); rev_row++)
{
    DataRow r_new = recovery_rows[rev_row];
    //  r_new = recovery_rows[rev_row];
    dt_sub.Rows.InsertAt(recovery_rows[rev_row], 0);
}
Sujit.Warrier
  • 2,815
  • 2
  • 28
  • 47

1 Answers1

1

You cannot add a DataRow to another DataTable, it has a reference to it's DataTable and throws an exception if you change the table.

You can use DataTable.ImportRow which imports the row and adds it to the end of the DataRowCollection. So the next task is to move it to the first position:

for (int rev_row = 0; rev_row < recovery_rows.Length; rev_row++)
{
    DataRow r_new = recovery_rows[rev_row];
    dt_sub.ImportRow(r_new);
    dt_sub.Rows.RemoveAt(dt_sub.Rows.Count - 1);
    dt_sub.Rows.InsertAt(r_new, 0);
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939