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.
DataView. Table. Copy() will copy the source DataTable, not the filtered data of the DataView.
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.
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.
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().
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;
dt = DataView.ToTable()
OR
dt = DataView.Table.Copy()
,
OR
dt = DataView.Table.Clone()
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With