Kamil
Kamil

Reputation: 13951

How to create new DataTable with column structure from other DataTable?

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 = ???;

Upvotes: 15

Views: 37511

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460370

Just use DataTable.Clone which clones the schema but not the data:

DataTable dtSecond = dtFirst.Clone(); // empty

Now you can start adding new rows:

DataRow newRow = dtSecond.Rows.Add();
newRow.SetField("column1", "Value1");
newRow.SetField("column2", "Value2");
newRow.SetField("column3", "Value3");

Upvotes: 9

Bridge
Bridge

Reputation: 30721

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();

Upvotes: 18

acermate433s
acermate433s

Reputation: 2554

use the Clone() method of the DataTable class.

Upvotes: 5

Related Questions