Follow @PDSAInc Cloning a DataRow - Paul Sheriff's Blog for the Real World

Paul Sheriff's Blog for the Real World

This blog is to share my tips and tricks garnered over 25+ years in the IT industry

Paul's Favorites

Cloning a DataRow

I can't even tell you how many times over the last few years I have had to clone a row from one DataTable to another DataTable. To make this easier, I created a method that I can call at anytime to create this new DataRow and return a new DataTable back to me. I have another overload of this method that I can also pass in the new DataTable. In ADO.NET there is no easy way to take a single row from an existing DataTable and copy it to another DataTable. The major reason why it is not so easy is you can not add a DataRow that exists in one DataTable to another DataTable. As a result you must create a new DataRow object and copy all of the values from the original DataRow into this new one. You can then create a new DataTable (or use one with the same structure), and add that DataRow to that new DataTable. Below is a method that you can call to accomplish the copying of a single row from one DataTable to a new DataTable.

C# Code

private DataTable CloneDataRow(DataTable dtOld, int rowNumber)
{
  DataRow dr;
  DataTable dtNew;

  dtNew = dtOld.Clone();

  dr = dtNew.NewRow();

  dr.ItemArray = dtOld.Rows[rowNumber].ItemArray;

  dtNew.Rows.Add(dr);

  return dtNew;
}

VB.NET Code

Private Function CloneDataRow(ByVal dtOld As DataTable, ByVal rowNumber As Integer) As DataTable
  Dim dr As DataRow
  Dim dtNew As DataTable

  dtNew = dtOld.Clone()

  dr = dtNew.NewRow()

  dr.ItemArray = dtOld.Rows(rowNumber).ItemArray

  dtNew.Rows.Add(dr)

  Return dtNew
End Function

I hope you find this method as helpful as I have found it over the years.

Good Luck With Your Coding,
Paul Sheriff

** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".

Posted: Aug 27 2009, 09:56 AM by psheriff | with 3 comment(s)
Filed under: ,

Comments

João Vitor PBC said:

private DataTable CloneDataRow(DataTable dtOld, int rowNumber)

{

 DataTable dtNew;

 dtNew = dtOld.Clone();

 dtNew.ImportRow(dtOld.Rows[rowNumber]);

 return dtNew;

}

# October 8, 2009 5:22 PM

anon said:

great tip, thanks

# October 28, 2009 1:35 AM

rom said:

Thanks for a very useful tip.

Amendment by João Vitor PBC is great too.

# October 28, 2010 6:39 AM

Matteo Conta said:

Thank you for your solution,really helpful

# January 19, 2012 9:52 AM