21

I need to copy a dataview into a datatable. It seems like the only way to do so is to iterate through the dataview item by item and copy over to a datatable. There has to be a better way.

Venkat
  • 2,549
  • 2
  • 28
  • 61
Ravedave
  • 1,158
  • 2
  • 11
  • 24

2 Answers2

62
dt = DataView.ToTable()

OR

dt = DataView.Table.Copy(),

OR

dt = DataView.Table.Clone();

Venkat
  • 2,549
  • 2
  • 28
  • 61
Jose Basilio
  • 50,714
  • 13
  • 121
  • 117
  • 1
    Thanks, google was failing me pretty badly. Hopefully this page will get ranked highly. – Ravedave Apr 20 '09 at 19:36
  • 11
    Note: `DataView.ToTable()` will only copy the values of the DataView. `DataView.Table.Copy()` will copy the source DataTable, not the filtered data of the DataView. `DataView.Table.Clone()` will only copy the structure of the source DataTable. – Homer Jun 26 '13 at 16:48
3

The answer does not work for my situation because I have columns with expressions. DataView.ToTable() will only copy the values, not the expressions.

First I tried this:

//clone the source table
DataTable filtered = dt.Clone();

//fill the clone with the filtered rows
foreach (DataRowView drv in dt.DefaultView)
{
    filtered.Rows.Add(drv.Row.ItemArray);
}
dt = filtered;

but that solution was very slow, even for just 1000 rows.

The solution that worked for me is:

//create a DataTable from the filtered DataView
DataTable filtered = dt.DefaultView.ToTable();

//loop through the columns of the source table and copy the expression to the new table
foreach (DataColumn dc in dt.Columns) 
{
    if (dc.Expression != "")
    {
        filtered.Columns[dc.ColumnName].Expression = dc.Expression;
    }
}
dt = filtered;
Homer
  • 7,594
  • 14
  • 69
  • 109