views:

308

answers:

1

When binding WPF Toolkit DataGrid to SQL database through LINQ to SQL, how to correctly set binding source:

should it be some generic collection, filled and updated by LINQ to SQL queries or there is a possibility to directly connect DataGrid with LINQ to SQL queries?

+1  A: 

As always, there is more than one way to skin a cat. However, I prefer to create a LINQ to SQL query and use the .ToList() to send the list to an ObservableCollection so you can monitor changes to your data and update the SQL Server database when your data is dirty. In other words, it would look something like this:

// Create an instance of your LINQ to SQL DataContext
LINQDataContext dc = new LINQDataContext();
var productQuery = from p in dc.Products select p;

// Create an ObservableCollection to hold your data and bind the DataGrid to this collection
public ObservableCollection<Product> Products {get; set;}
Products = new ObservableCollection<Product>(productQuery.ToList());

But of course, if you're needing to perform filters, grouping, or sorting, I would send the query to a ListCollectionView instead. Which would look like this:

public ListCollectionView Products {get; set;}
Products = new ListCollectionView(productQuery.ToList());

Hope that helps!

Brent