Here, I will demonstrate the functionality of DataTable’s ImportRow & Clone methods and the difference between the Rows.Add & ImportRow.
Clone method will copy the structure of the existing table, only Columns and Schema, not the data. So in the following
DataTable dt = GetSomeVal(); DataTable dt1 = dt.Clone();
DataTable dt1 = new DataTable(); DataRow dr1 = dt1.NewRow(); DataTable dt2 = new DataTable(); // will throw an error as dr1 already belongs to another datatable dt2.Rows.Add(dr1); // will execute adding a new row to dt2 Table dt2.ImportRow(dr1); dt1.Rows.Add(dr1);
The above code is pretty much self-explanatory. If you have to add a DataRow from a different DataTable use ImportRow method otherwise use Rows.Add.
Happy Coding …