If you try to add a DataRow to DataTable using Rows.Add() Method you will get "This row already belong to another table" Error.
Wrong Way To Add DataRow
DataTable DataTableOriginal = new DataTable();
DataTable DataTableDuplicate = new DataTable();
foreach (DataRow
dr in DataTableOriginal.Rows)
{
// if you add like this you will get an error
DataTableDuplicate.Rows.Add(dr);
}
Correct Way To Add DataRow
DataTable DataTableOriginal = new DataTable();
DataTable DataTableDuplicate = new DataTable();
// the clone method copies the structer of datatableorginal
to datatableduplicate
DataTableDuplicate = DataTableOriginal.Clone();
foreach (DataRow
dr in DataTableOriginal.Rows)
{
//importrow method copies the datarow to
datatableduplicate which has the correct structure
DataTableDuplicate.ImportRow(dr);
}
Explanation:
To add or copy a DataRow form one Datatable to another Datatable
1. we need to copy the structure of the the data table that is to be copied using clone() method.
2. Copy the datarow from one table to another using ImportRow() method.
No comments:
Post a Comment