7

In a Telerik control, I was able to bind a DataTable directly to the ItemSource, but when I switched to the Codeplex WPFToolkit Datagrid:

<dg:DataGrid Name="theGrid"/>
---
theGrid.ItemsSource = dt;

I get this error:

Cannot implicitly convert type 'System.Data.DataTable' to 'System.Collections.IEnumerable'.

How can I bind the DataTable to theWPFToolkit DataGrid?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047

4 Answers4

32

I find the easiest way is:

myDataGrid.ItemsSource = myDataTable.DefaultView;

because DefaultView implements IEnumerable

viggity
  • 15,039
  • 7
  • 88
  • 96
  • 1
    +1, binding to a DataView is simple and works great, especially if you want to be able to navigate relations. – Oskar Jun 04 '09 at 12:19
4

I'm assuming support for this will be added in the future, but for now you can use the implementation of IListSource on DataTable. Call the GetList() method and use that as your data source. It's an explicit interface implementation so you'll need to cast:

var data = (myDataTable as IListSource).GetList();
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • I found this: http://msdn.microsoft.com/en-us/library/aa325664(VS.71).aspx but how do I use the implementation of IListSource on DataTable in order to call the GetList() method? – Edward Tanguay Feb 02 '09 at 10:43
3

You'll have to project your datatable into something that implements IEnumerable as that is waht the DataGrid expects. The grid is a different implementation to the Telerik version so its hard to expect the same functionality from both.

Ray Booysen
  • 28,894
  • 13
  • 84
  • 111
  • This worked, in fact I was converting from an List to the Datatable for the Telerik control so this is even easier, I just use the original List object now, thanks. – Edward Tanguay Feb 02 '09 at 11:12
0

In such cases I bind ItemsSource to DataContex in XAML i.e.

ItemsSource={Binding} 

and then in codebehind I do

theGrid.DataContext = dt

This will help.

Mxyk
  • 10,678
  • 16
  • 57
  • 76