16

I have a row collection (DataRow[] rows). And I want to import all rows to another DataTable (DataTable dt).

But how?

Code

DataTable dt;
if (drs.Length>0)
{
    dt = new DataTable();

    foreach (DataRow row in drs)
    {
        dt.Columns.Add(row???????)
    }

    // If it possible, something like that => dt.Columns.AddRange(????????)

    for(int i = 0; i < drs.Length; i++)
    {
        dt.ImportRow(drs[i]);
    }
}
Community
  • 1
  • 1
uzay95
  • 16,052
  • 31
  • 116
  • 182

4 Answers4

25

Assuming the rows all have the same structure, the easiest option is to clone the old table, omitting the data:

DataTable dt = drs[0].Table.Clone();

Alternatively, something like:

foreach(DataColumn col in drs[0].Table.Columns)
{
    dt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 2
    If you're using .NET 3.5, could you use the DataTableExtensions.CopyToDataTable method (extension to DataRowCollection / IEnumerable) ? – Alan McBee May 11 '09 at 19:48
5

If your DataRows is from a Data Table with Columns defined in it,

DataRow[] rows;

DataTable table = new DataTable();
var columns = rows[0].Table.Columns;

table.Columns.AddRange(columns.Cast<DataColumn>().ToArray());

foreach (var row in rows)
{
    table.Rows.Add(row.ItemArray);  
}
Sathish Naga
  • 1,366
  • 2
  • 10
  • 18
1

Try this:

// Assuming you have a DataRow object named row:
foreach(DataColumn col in row.Table.Columns)
{
    // Do whatever you need to with these columns
}
Artorias2718
  • 575
  • 5
  • 11
1

How about

DataTable dt = new DataTable;
foreach(DataRow dr in drs)
{
    dt.ImportRow(dr);
}

Note this only works if drs is a DataRowCollection. Detached rows (not in a DataRowCollection are ignored).

Don't forget to call AcceptChanges.

Alan McBee
  • 4,202
  • 3
  • 33
  • 38
  • I've done a quick check, and that doesn't add any columns... so you get rows without any values - not especially useful. – Marc Gravell May 10 '09 at 19:09
  • Re `DataRowCollection` - it doesn't make any difference. My test sample is using an attached row from a DataTable.Rows (a DataRowCollection) - and it simply doesn't work. Sorry. – Marc Gravell May 10 '09 at 19:14
  • ok, I answered from memory, not a test case (hard to get back and forth from my test environment, don't ask). I withdraw my anwer. – Alan McBee May 10 '09 at 22:51