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".

4 Comments

Comments have been disabled for this content.