DataGrid:Deleting the Selected Rows

Deleting the selected row(s) requires you to get the bound collection or collection view and enumerate
through the SelectedItems property of the DataGrid, removing the corresponding item from the bound
collection/collection view. This is can be somewhat of a messy process due to removing items in an
enumerated collection, but the use of LINQ can simplify the code somewhat:
ObservableCollection<Product> collection =
productDataGrid.ItemsSource as ObservableCollection<Product>;
// Convert the SelectedItems property to an array so its enumerator won't be
// affected by deleting items from the source collection
// Note that this line requires the System.Linq namespace to be declared
var removeItems = productDataGrid.SelectedItems.Cast<Product>().ToArray();
foreach (Product product in removeItems)
collection.Remove(product);

Alternatively, you can force only one row to be selected at a time in the DataGrid by setting its
SelectionMode property to Single (rather than the default value of Extended), meaning that you only
need to worry about removing a single selected item. In this case, the following code would suffice:
ObservableCollection<Product> collection =
productDataGrid.ItemsSource as ObservableCollection<Product>;
collection.Remove(productDataGrid.SelectedItem as Product);

posted @ 2012-06-17 18:44  Ken-Cai  阅读(233)  评论(0编辑  收藏  举报