Search code examples
c#datatableinsertrow

Insert a row from one DataTable in the middle of another DataTable


So, I have two DataTables. I can easly ADD rows from one to another with this: table1.Rows.Add(table2.Rows[0].ItemArray);

But I want to insert the row in particular place, not on the bottom of the table1. Tried to use the table1.Rows.InsertAt, but the problem with it is that you need the DataRow class (which I can't figure out how to get), and also you can't do table.Rows.InsertAt(table1.Rows[0], idex); because it says that the row belongs to another table. (table2 is source, table1 - target)


Solution

  • You can clone the source row's items and then create a DataRow using them:

    var sourceItems = (object[])(table2.Rows[0].ItemArray.Clone());
    
    DataRow targetRow = table1.NewRow();
    targetRow.ItemArray = sourceItems; 
    table1.Rows.InsertAt(targetRow, index);
    

    (note that it's not clear in your question which datatable is the source and which is the target, I assumed table2 is the source and table1 the target)