Transferring Data between DataTables

How do I import rows from one datatable to another.Calling the ImportRow function imports the rows at the end of the datatable.I want to be able to import it at a specific index.Data is displayed using a DataGrid.

I tried using InsertAt function but as I have to add one row at a time iterating thro the loop thows an Exception.(System.ArgumentException - row belongs to another table).

Is this even possible. if so where do I specify the index at which the rows need to be imported.

Thanks in advance




Answer this question

Transferring Data between DataTables

  • Wayne Atherton

    Hi!

    What you are doing is like you have table A & B. You want to import row from B to A at certain index. You'll have to use loop and in the loop for each row you'll have to create new row for A and assign values to its columns in the loop from the current row of B and then Insert it at required index. This should work, otherwise post your code.

    What you are doing is trying to Insert the row B to A which its not allowing and hence throwing exception.

    cheers.



  • Detlef S.

    Hi!

    yes it doesn't work and I don't know why but you can still solve your problem if this is not the only way you are looking for.

    Instead of this:

    row.ItemArray.CopyTo(dr.ItemArray,0);

    Use following:

    dr[0] = row[0];

    dr[1] = row[1];

    and so on.... and then you can insert the row whereever you want.

    cheers.



  • GeorgeBush

    Thanks
  • kumar 123

    Thanks Guys for your posts.The Insert seems easy to use but doesn't work in my case as the col names can change on depending on what the user wishes to see.

    Creating new rows in table A and assigning values from table B worked but for some reason Table A shows null values for the imported rows.Any explanations..

    My Code is as follows:

    DataView dv = new DataView();//View for the Table A

    DataRow dr;

    for(int i = 0;i<=dv.Table.Rows.Count-1;i++)

    {

    if(dg.IsSelected(i))//getting the selected index from the datagrid

    {

    if (table.Rows.Count >0)

    {

    foreach(DataRow row in table.Rows)//table is the name of Table B

    {

    //dv.Table.ImportRow(row);

    dr = dv.Table.NewRow();

    row.ItemArray.CopyTo(dr.ItemArray,0);

    dv.Table.Rows.InsertAt(dr,i+1);

    }

    }

    dv.Table.AcceptChanges();

    }

    Thanks once again for all your help


  • lostantipodean

    Thanks Sohail,that works..
  • desifunde

    you can always use something like this that avoids the need for a loop

    Insert Into TableA (firstname, lastname)

    Select firstname, lastName from TableB where rowID > 50


  • mschetu

    Hi Reeba

    Mark it as answer so that other could benefit as well

    cheers



  • Transferring Data between DataTables