0

I want to create a copy of a datatable. I am not sure what is the correct way to do it. So, I decided to use

DataTable filteredData = sourceDataTable.Select(expression).CopyToDataTable();

as mentioned in this post - How to pass DataTable.Select() result to a new DataTable?

I tried to use it by setting expression = "where 'TRUE' = 'TRUE'". I hoped that this will not filter any rows from original data table, ie full copy. But, I got the error - System.Data.SyntaxErrorException: Syntax error: Missing operand after ''TRUE'' operator.

How do I copy a datatable easily ?

Community
  • 1
  • 1
Steam
  • 9,368
  • 27
  • 83
  • 122

2 Answers2

3

You can use the DataTable.Copy method.

Copy creates a new DataTable with the same structure and data as the original DataTable.

var copiedDataTable = sourceDataTable.Copy();
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
2

As from Winney response you could use DataTable.Copy (and probably is the best option in your case), but if you still want to use Select then don't pass any filter expression

 DataTable filteredData = sourceDataTable.Select().CopyToDataTable();

DataTable.Select has an overload that doesn't accept any parameter and thus select everything is present in the DataTable

Steve
  • 213,761
  • 22
  • 232
  • 286