The Sample Application > Implement the Client Side > Synchronize the Views |
Our master-detail view is not synchronized yet. All products are displayed in the bottom grid, regardless of the category selected on the top grid.
To synchronize the views, we need to handle the SelectionChanged event on the categories grid and filter the products to display only those that belong to the selected category.
To do this, we start by adding an event handler to the page constructor:
C# |
Copy Code |
---|---|
public Page()
{
InitializeComponent();
LoadData();
_gridCategories.SelectionChanged += _gridCategories_SelectionChanged;
} |
Implement the event handler as follows:
C# |
Copy Code |
---|---|
void _gridCategories_SelectionChanged(object sender, EventArgs e) { var drv = _gridCategories.SelectedItem as DataRowView; if (drv != null) { var dv = _ds.Tables["Products"].DefaultView; dv.RowFilter = string.Format("CategoryID = {0}", drv.GetData("CategoryID")); } } |
The code gets the selected category as a DataRowView object, gets the default view for the "Products" table (used as a data source for the second grid), and applies the filter. Again, the code looks familiar to WinForms and ASP.NET developers.
If you run the application again, notice that the views are now synchronized.
Note that instead of applying a filter to the DataView, we could have used a LINQ query to update the products table. For example:
C# |
Copy Code |
---|---|
void _gridCategories_SelectionChanged(object sender, EventArgs e) { var drv = _gridCategories.SelectedItem as DataRowView; if (drv != null) { int id = (int)drv.GetData("CategoryID"); _gridProducts.ItemsSource = from dr in _ds.Tables["Products"].Rows where (int)dr["CategoryID"] == id select dr.GetRowView(); } } |
This also achieves the goal of synchronizing the master and detail views. The main difference is that the previous method would affect any other controls bound to the same view, while this method affects only the products grid.