how to copy only the columns in a DataTable to another DataTable?
DataTable.Clone()
should do the trick.
DataTable newTable = originalTable.Clone();
If only the columns are required then DataTable.Clone()
can be used. With Clone
function only the schema will be copied. But DataTable.Copy()
copies both the structure and data
E.g.
DataTable dt = new DataTable();
dt.Columns.Add("Column Name");
dt.Rows.Add("Column Data");
DataTable dt1 = dt.Clone();
DataTable dt2 = dt.Copy();
dt1
will have only the one column but dt2
will have one column with one row.
Datatable.Clone
is slow for large tables. I'm currently using this:
Dim target As DataTable =
New DataView(source, "1=2", Nothing, DataViewRowState.CurrentRows)
.ToTable()
Note that this only copies the structure of source table, not the data.
If you want the structure of a particular data table(dataTable1) with column headers (without data) into another data table(dataTable2), you can follow the below code:
DataTable dataTable2 = dataTable1.Clone();
dataTable2.Clear();
Now you can fill dataTable2 according to your condition. :)