locked
copy a datarow from one table to another RRS feed

  • Question

  • I would like to take a row, and add it to an empty table but the row belongs to a table how do i copy the row so the 2 rows and tables are disconected?

     DataTable dt = ds.Tables[0].Clone();
     dt.Rows.Add(Row);  here i get errror "This row already belongs to another table."

    McC
    Thursday, June 25, 2009 8:55 PM

Answers

  • You can also try the code below but remember to make sure the columns in both tables match
    Dim dt As New DataTable
    Dim newdr As DataRow
    
    newdr = dt.NewRow
    newdr.ItemArray = DataRowToCopy.ItemArray
    dt.Rows.Add(newdr)

    Thursday, June 25, 2009 9:38 PM

All replies

  • Odd? .Clone() does not copy data forward.
    Try issuing a dt.Clear();

    You can also use dt.ImportRow(Row) instead of dt.Rows.Add(Row)
    Thursday, June 25, 2009 9:10 PM
  • You can also try the code below but remember to make sure the columns in both tables match
    Dim dt As New DataTable
    Dim newdr As DataRow
    
    newdr = dt.NewRow
    newdr.ItemArray = DataRowToCopy.ItemArray
    dt.Rows.Add(newdr)

    Thursday, June 25, 2009 9:38 PM
  • Clone of a DataTable only clones the schema. Copy will copy the data, call clone first then copy. If you need to copy a row to a new table you can use clone to clone a new one, but if you want to add this to another table  i would use Merge or ImportRow.

    http://msdn.microsoft.com/en-us/library/system.data.datatable.importrow.aspx

    Thanks
    Chris Robinson
    Program manager - DataSet


    This posting is provided "AS IS" with no warranties, and confers no rights.
    Friday, June 26, 2009 2:25 AM
  • Thanks, that instantly remedied my code.  I then had/have another problem that would be helpful if you have knowledge of:

    Upon Importing the row I continually recieve the error: DBNull occurred and I'm testing for the strongly typed data being null hence I don't understand how to trap for the situation.  I'm iterating each row of a DataTable and upon finding particular rows, I add them to a second filtered table.  This is where I recieve the DBNull error - upon adding a particular row to the filtered DataTable even though I check for there being a null value in the row.

    Thanks!

    Glenn


    Glenn T. Kitchen VB.NET Forums

    Friday, August 17, 2012 7:39 PM
  • Glenn, could you post your code?

    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

    Sunday, August 19, 2012 4:52 PM
  • DataTable dt ;  // Containing data
    DataTable dt1= dt.Clone(); 
    
    foreach (DataRow dr in dt.Rows)
    {
        dt1.ImportRow(dr);
    }
    Thursday, April 11, 2013 7:39 AM