How to display data from related tables in a WPF datagrid
I typically just set the DataGrids ItemSource to a DataTable in the code behind. This is easier than XAML if you are going to be changing the ItemSource between more than one DataTable.
myDataGrid.ItemsSource = myTable.DefaultView;
Anytime I want to change what my datagrid is showing, I simply update the ItemsSource. That way I can manipulate my DataTable's in any way I want, and then see the outcome via the DataGrid.
Update
To join data from both tables run a Linq join to create an IEnumberable of fields you want in your table. Then convert your IEnumerable back to a DataTable for display. I use this method to convert an IEnumerable to a DataTable.
the_mandrill
Updated on June 04, 2022Comments
-
the_mandrill almost 2 years
I'm just finding my way with WPF/Datagrid/Linq and I'm trying to find out how to display data from a related table in my datagrid. For example I have 3 tables:
- Customers: id, name
- Products: id, name
- Orders: id, customerId, productId
and I've set up the relations in the DB tables. I've added the tables as a C# DataSet which has created my wrapper classes. I now want to bind a query to a couple of different WPF datagrids to obtain the following:
- list of orders as | Order Id | Product name | Customer Name |
- list of customers as | Customer Name | Summary of orders (eg comma separated list of strings) |
How can I specify the DataContext or ItemsSource in my XAML to display this information from other tables? I'm using
ObjectDataProvider
s to provide design-time support, if that makes any difference.I've seen this question: How to bind WPF Datagrid to a joined table which creates a new class to display the information for the table. Is this how I need to do it rather than specifying a binding?
EDIT:
I've had a bit of success using the 2nd method above. I wonder though whether I can use bindings to achieve the same thing without needing to do an explicit
select
query to create the new items. I've got a query that I map to the datagrid:var q = from d in dbMan.dataset.Orders select new { id=d.id, productName = d.ProductsRow.name, custName = d.CustomersRow.name };
and then bind in the XAML:
<my:DataGrid.Columns> <my:DataGridTextColumn Header="id" Binding="{Binding id}" /> <my:DataGridTextColumn Header="Product Name" Binding="{Binding productName}" /> <my:DataGridTextColumn Header="Customer Name" Binding="{Binding custName}" /> </my:DataGrid.Columns>