views:

1250

answers:

3

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

BUT HOW !?

        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]);
            }
         }

Do you have any idea ?

+2  A: 

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
Thank you Marc. You are perfect.
uzay95
If you're using .NET 3.5, could you use the DataTableExtensions.CopyToDataTable method (extension to DataRowCollection / IEnumerable<DataRow>) ?
Alan McBee
+1  A: 

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
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
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
Yes it doesn't work without adding columns before import.
uzay95
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
+1  A: 

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
This is also very good. I perfer AddRange instead of foreach.
uzay95