Binding an ADO.NET Entities Framework data source to a WPF DataGrid control
Posted: (EET/GMT+2)
If you happen to be writing database applications with WPF (Windows Presentation Foundation) and want to display data in a DataGrid component, then you are in good hands. Especially with Visual Studio 2010 and .NET 4.0, there isn't much code you need to write if you want to display data from an Entity Data Model (EDM) in the grid.
Shortly put, a WPF DataGrid control contains a property called ItemsSource (notice the double-S in the name) to which you can assign any ADO.NET Entity Framework entity object, LINQ query results, and so on. For instance, if you started an empty WPF project and wanted to display the Customers table data in a blank DataGrid, you might be tempted in writing code like this:
// take #1 NorthwindEntities entities = new NorthwindEntities(); dataGrid1.ItemsSource = entities.Customers;
However, if you run the above code, you will get no errors, but the datagrid stays empty. Why? This happens because the datagrid cannot directly work with entity data model "table" entities, and thus, you need a slight addition to the above code (note the end of the last line):
// take #2 NorthwindEntities entities = new NorthwindEntities(); dataGrid1.ItemsSource = entities.Customers.ToList();
However, this again runs, but the grid still stays empty. Why? Because you didn't ask the grid to render any columns. To do this, you would either need to create a set of columns manually, or ask the grid to do the work for you using the AutoGenerateColumns Boolean property.
That said, here is the final, working code:
// take #3, a success NorthwindEntities entities = new NorthwindEntities(); dataGrid1.AutoGenerateColumns = true; dataGrid1.ItemsSource = entities.Customers.ToList();
On MSDN, there's a more elaborate version of this short tutorial. Good luck!