Converting DataRow[] to DataTable (Error: This row already belongs to another table) | Quisitive
Converting DataRow[] to DataTable (Error: This row already belongs to another table)
November 19, 2012
Quisitive
In this blog, we will go through converting DataRow[] to DataTable. Find out what's the best way of doing this conversion seamlessly.

For those of us still actually supporting ADO.NET applications, I thought I would jot this one down. J

I wanted to convert a DataRow[] to a DataTable. While DataRow[] are nice, unfortunately they do not support all of the nice features of a DataTable, such as filtering and sorting. Since I needed to further evaluate and sort the DataRow[], I decided that it would be a good idea to go ahead and convert it to a DataTable. Turns out, there is no straight conversion available, so you basically have to create a DataTable and add the rows from the DataRow[] objects. I initially started with this:

// DataTable: Results
// DataRow[]: FilteredResults
public DataTable ConvertToDataTable(DataRow[]FilteredResults)
{
     DataTable dt = new DataTable();
     foreach (DataRow dr in FilteredResults)
{
dt.Rows.Add(dr);
}
return dt;    

However, when I ran this code, the application threw the following exception: This row already belongs to another table. It turns out I was ALMOST right, but needed to make a couple of modifications: 1) I needed to create a new DataTable that was a clone of the original DataTable; 2) I needed to use the ImportRow() method rather than the Rows.Add() method.

// DataTable: Results 
// DataRow[]: FilteredResults
public DataTable ConvertToDataTable(DataTable Results, DataRow[] FilteredResults)
{
     DataTable dt = Results.Clone();
foreach (DataRow dr in FilteredResults)
{
dt.ImportRow(dr);
}
return dt;    
}