As in title - the question is:
How to create new DataTable with column structure from other DataTable?
I need empty DataTable to use .Rows.Add()
method in it.
Code:
DataTable dtFirst = new DataTable();
dtFirst.Columns.Add("column1");
dtFirst.Columns.Add("column2");
dtFirst.Columns.Add("column3");
FillDataTableFirst(); // before I create second DataTable - dtFirst is filled
// here I need dtSecond DataTable with same column structure
// i cant just copy first data table, because it contains data
DataTable dtSecond = ???;
You are looking for the DataTable.Clone()
method (available since framework version 1.1).
From the documentation:
Clone creates a new DataTable with the same structure as the original DataTable, but does not copy any data (the new DataTable will not contain any DataRows). To copy both the structure and data into a new DataTable, use Copy.
In your example:
DataTable dtFirst = new DataTable();
dtFirst.Columns.Add("column1");
dtFirst.Columns.Add("column2");
dtFirst.Columns.Add("column3");
FillDataTableFirst(); // before I create second DataTable - dtFirst is filled
DataTable dtSecond = dtFirst.Clone();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With