Copy source datatable to destination datatable with the schema of destination

186 Views Asked by At

I'm trying to copy the data from source dt to destination datatable. source datatble types are sting and destination datatble types contains datetime along with strings.

datatable dt2=new datatable();
foreach (DataRow row in dt1.Rows)
{            
     dt2.ImportRow(row); //String was not recognized as a valid DateTime.
}

I get String was not recognized as a valid DateTime as destination column type is datetime and is not able to import that row.

1

There are 1 best solutions below

1
mitchsnitchel On

Use DataTable.Clone() to setup a new DataTable object with the existing schema. Then add any additional columns you might need.

DataTable dt1 = MyData();
DataTable dt2 = dt1.Clone();
foreach(DataRow row in dt1.Rows)
{
    dt2.ImportRow(row);
}