Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a DataTable to a DataTable

Tags:

c#

datatable

wpf

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]);
}
like image 521
KMC Avatar asked May 25 '26 23:05

KMC


1 Answers

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:

        DataTable dataTable2  = dataTable1.Clone();  
        dataTable2.Columns.Remove("column1");
        dataTable2.Columns.Remove("column2");
like image 173
platon Avatar answered May 27 '26 13:05

platon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!