1

I'm retrieving DataTables from my database and I need to insert a particular row from one DataTable into a determined index into another DataTable.

basically I would like to have say, row[0] of DataTable dt1 inserted into DataTable dt2 at index 4.

These are two different tables obtained from two different database calls. Is there a way to do this?

Any help would be greatly appreciated.

[EDIT] Sorry, Here's what I've done

DataTable dt1 = populateTable();
DataTable targetTable = populateTargetTable();
DataRow dr;
dr = dt1.NewRow();
dr = targetTable.Rows[0];

int index=0;
DataRow temp;
for (int i = 0; i < dt1.Rows.Count; i++)
{
    temp = dt1.Rows[i];
    if (rowFitsCondition(temp)){
        index = i;
    }
}
dt1.Rows.InsertAt(dr, index);

and the InsertAt() call fails, and gives me the This row already belongs to another table error.

shadonar
  • 1,114
  • 3
  • 16
  • 40
  • This seems like a non-issue. Read the data from one table insert it into another table -- standard ETL stuff. What exactly is your question, why can't you just write the code? – Hogan Dec 06 '13 at 15:53
  • is these both datatable have same schema? – Bhavesh Kachhadiya Dec 06 '13 at 15:53
  • Have you tried any thing? – Bhavesh Kachhadiya Dec 06 '13 at 15:55
  • And what does not work? – StingyJack Dec 06 '13 at 16:02
  • @StingyJack the `InsertAt()` call fails, and gives me the `This row already belongs to another table` error. – shadonar Dec 06 '13 at 16:03
  • @StingyJack that link suggests the `ImportRow()` which doesn't allow for an insert to a specific index. If that's really the only way to do it I guess I'll have to create a temp `DataTable` to import the rows from the `dt1` and once I reach the particular index then import the row from the `targetTable` and afterwards continue importing the remaining rows from `dt1` – shadonar Dec 06 '13 at 16:09
  • Please read the rest of the first answer, but it seems odd to worry about index order in a data table. Typically you would use a DataView to determine how to display data, and .Select() to choose rows from the table. – StingyJack Dec 06 '13 at 16:10

2 Answers2

4

try with Clone

dr= dt1.NewRow();
dr.ItemArray = targetTable.Rows[0].ItemArray.Clone() as object[]; 
dt1.Rows.InsertAt(dr, index);
Damith
  • 62,401
  • 13
  • 102
  • 153
0

The row exists as part of the source table. You need to create a new row in the target table and copy the relevant values from the source to the target row, then add the target row to the target table.

This linked duplicate has a few ways to accomplish this.

Community
  • 1
  • 1
StingyJack
  • 19,041
  • 10
  • 63
  • 122