Convert and use DataTable in WPF DataGrid?

c#, datagrid, wpf

Solution

In WPF you don't do this

DataGrid.ItemsSource = DataTable;

Instead you do

 DataGrid.ItemsSource = DataTable.AsDataView();

In order to get DataTable back you can do something like this

public static DataTable DataViewAsDataTable(DataView dv)
{
    DataTable dt = dv.Table.Clone();
    foreach (DataRowView drv in dv)
       dt.ImportRow(drv.Row);
    return dt;
}

DataView view = (DataView) dataGrid.ItemsSource;
DataTable table = DataViewAsDataTable(view)

Problem

In normal WinForm application you can do that: ``` DataTable dataTable = new DataTable(); dataTable = dataGridRecords.DataSource; ``` but how to do that with the WPF datagrid? ``` dataTable = dataGridRecords.ItemsSource; ``` won't work either.

Original source