Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = ???;
like image 482
Kamil Avatar asked Sep 25 '13 15:09

Kamil


1 Answers

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();
like image 174
Bridge Avatar answered Sep 28 '22 12:09

Bridge