views:

38

answers:

1

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 ObjectDataProviders to provide design-time support, if that makes any difference.

I've seen this question: http://stackoverflow.com/questions/1863621/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>
+1  A: 

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.

jsmith
How do I get this to combine the fields from more than one table though?
the_mandrill
Thanks -- those extra steps of having to do a join, then conversion to DataTable weren't obvious to me.
the_mandrill