Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get columns from a datarow?

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]);
    }
}
like image 665
uzay95 Avatar asked May 10 '09 18:05

uzay95


4 Answers

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);
}
like image 171
Marc Gravell Avatar answered Oct 06 '22 00:10

Marc Gravell


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);  
}
like image 42
Sathish Naga Avatar answered Oct 06 '22 01:10

Sathish Naga


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.

like image 25
Alan McBee Avatar answered Oct 06 '22 00:10

Alan McBee


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
}
like image 32
Artorias2718 Avatar answered Oct 06 '22 00:10

Artorias2718