.NET Compact Framework Workaround For Missing DataTable .Copy() Method

By Robbe D. Morris

Printer Friendly Version

Robbe Morris
Robbe & Melisa Morris
The current release of the .NET Compact Framework (comes with Visual Studio .NET 2003) is missing the .Copy() method on the DataTable class.  The .Copy() method enables the developer to create an exact copy of the DataTable structure and data without any references to its parent DataSet tagging along.  In one of my recent projects, I had the need to extract various DataTables from a DataSet and create new DataSets out of combinations of these tables.  The .Copy() was exactly what I needed.  So, since that method wasn't available, I whipped up this little code sample below and used it instead.


Sample Code
   public DataTable CopyDataTable(DataTable OldTable)
  {
    DataTable NewTable = new DataTable();
    DataRow NewRow = null;
    try
    {
      NewTable = OldTable.Clone();
      foreach(DataRow OldRow in OldTable.Rows)
      {
        NewRow = NewTable.NewRow(); 
        NewRow.ItemArray = OldRow.ItemArray; 
        NewTable.Rows.Add(NewRow);
      }
    }
    catch (Exception) { throw; }
    return NewTable;
  }

Robbe has been a Microsoft MVP in C# since 2004.  He is also the co-founder of NullSkull.com which provides .NET articles, book reviews, software reviews, and software download and purchase advice.