I want to assign a DataTable (dataTable1) to another DataTable (dataTable2) and remove some columns in the latter DataTable. For example I have the following code:
DataTable dataTable2 = dataTable1;
dataTable2.Columns.Remove("column1");
dataTable2.Columns.Remove("column2");
It turns out both DataTable (dataTable1 and dataTable2) have the columns removed. I do not understand why dataTable1 would have column1 and column2 removed as well, while I am only removing columns in dataTable2.
[EDITED – with answer]
Should use Clone() AND ImportRow() instead of a pointer assignment.
DataTable dataTable2 = dataTable1.Clone()
for (int i = 0; i < dataTable1.Rows.Count; i++)
{
dataTable2.ImportRow(dataTable1.Rows[i]);
}
This happens because dataTable2 points to the same table as dataTable1. To resolve this problem, use the DataTable’s Clone method to create a new DataTable with the same structure: