Convert a DataRow[] to DataTable without losing its DataSet

Dante picture Dante · Jun 29, 2012 · Viewed 36.7k times · Source

I am working with DataSets and DataTables in C#.

My first problem was how to convert a DataRow[] object to DataTable, which I solved with this link:

simple-way-to-convert-datarow-array-to-datatable

So, What I did was the following:

// Gets the rows according to the relation
DataRow[] rows = someDataRow.GetChildRows("the_table_relation");
DataTable newDataTable = rows.CopyToDataTable<DataRow>();    

All the data that I am work with is in a single DataSet, so, my problem is that my object newDataTable does not contain the reference to my DataSet anymore (ie newDataTable.DataSet is equal to null).

Is there a way to make the conversion without losing the reference to my DataSet??

Hope someone can help me.

Thanks in advance

Answer

Jon Skeet picture Jon Skeet · Jun 29, 2012

Presumably you already have a DataTable? If so, use an overload of CopyToDataTable which takes the existing table as an argument:

rows.CopyToDataTable<DataRow>(existingTable, LoadOption.Upsert);

Alternatively, could you just use DataTableCollection.Add(DataTable)?

dataSet.Tables.Add(table);