This is something that I expected to be straightforward – binding a DataTable to a WPF DataGrid. The problem is that DataTable doesn’t implement IEnumerable, and unfortunately that’s what the DataGrid’s ItemsSource property requires.
Fortunately for us, there’s a really simple workaround. DataTable has a property named DefaultView, which returns a DataView that can be used for binding purposes.
// some example data.
DataTable myDataTable = new DataTable();
// Add columns to DataTable.
myDataTable.Columns.Add("Column A");
myDataTable.Columns.Add("Column B");
// Add some rows to the DataTable.
myDataTable.Rows.Add("A1", "B1");
myDataTable.Rows.Add("A2", "B2");
myDataTable.Rows.Add("A3", "B3");
// Bind DataTable to DataGrid.
myDataGrid.ItemsSource = myDataTable.DefaultView;
The original purpose for the DataView is for custom sorting and filtering, but it works out great for a quick and easy way to make DataTables bindable. Hopefully this will save you some time and an unexpected compile error when you need to populate a DataGrid with a DataTable.