3

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

Community
  • 1
  • 1
Dante
  • 3,208
  • 9
  • 38
  • 56

3 Answers3

11

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);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Thank you for your reply, but unfortunately for some reasons I need to convert the DataRow[] object to a new DataTable without losing its DataSet reference – Dante Jun 29 '12 at 19:55
4
 DataView DV = MyDataTable.AsDataView();
 DV.RowFilter = "Id = '" + RecordId + "'";
 DataTable newDataTable = DV.ToTable();
lady
  • 356
  • 1
  • 2
  • 14
1

I believe the solution may be contained in Jon Skeet's answer dataSet.Tables.Add(newDataTable)

The thing is that the newDataTable doesn't have a DataSet child control but rather a DataSet parent control. That is, a DataSet can contain Tables while the newDataTable's DataSet is the "DataSet that owns newDataTable" which in the case of the table you're creating above is null until added to a DataSet.

Dan Norton
  • 362
  • 1
  • 5
  • 17