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);

转载于:https://www.cnblogs.com/Ken-Cai/archive/2012/06/17/2552787.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值