Monday, September 2, 2013

Copy a datatable into another datatable in C#


From the title this sound as simple as doing this:

                foreach (DataRow dr in dt.Rows)
                {
                    dttemp.Rows.Add(dr);
                }

But it does not work this way, It gives error  that data row belongs to another table . So, how would you copy a datatable into another datatable:
First have to clone the structure of datatable:           
            dttemp = dt.Clone();

And, then need to import the rows:

                foreach (DataRow dr in dt.Rows)
                {
                           //Conditional copy
                        dttemp.ImportRow(dr);
                   
                }

For copying complete datatable, we have:

dttemp = dttemp.Copy();