Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to copy a dataview to a datatable in C#?

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.

like image 786
Ravedave Avatar asked Apr 20 '09 19:04

Ravedave


People also ask

How copy data from DataView to DataTable in C#?

DataView. Table. Copy() will copy the source DataTable, not the filtered data of the DataView.

How do you convert a data view into a DataTable?

In addition, if you need to create a new DataTable from the DataView, you can use the ToTable method to copy all the rows and columns, or a subset of the data into a new DataTable. The ToTable method provides overloads to: Create a DataTable containing columns that are a subset of the columns in the DataView.

What is DataTable DataView?

A DataView enables you to create different views of the data stored in a DataTable, a capability that is often used in data-binding applications. Using a DataView, you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression.

How do I copy the structure of a DataTable to another DataTable in C#?

Copy() creates a new DataTable with the same structure and data as the original DataTable. To copy the structure to a new DataTable, but not the data, use Clone().


2 Answers

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;
like image 42
Homer Avatar answered Sep 24 '22 14:09

Homer


dt = DataView.ToTable()

OR

dt = DataView.Table.Copy(),

OR

dt = DataView.Table.Clone();

like image 115
Jose Basilio Avatar answered Sep 21 '22 14:09

Jose Basilio