开发者

silverlight delete row with delete key

开发者 https://www.devze.com 2023-03-13 14:02 出处:网络
I want to delete all the selected rows when the delete button is pressed. I assumed that as log as开发者_开发百科 the datagrid is bound to an ObservableCollection the effect of hitting delete was to d

I want to delete all the selected rows when the delete button is pressed. I assumed that as log as开发者_开发百科 the datagrid is bound to an ObservableCollection the effect of hitting delete was to delete the item from the collection.

It seems this is not working, here is what I've tried:

private void historyGrid_KeyUp(object sender, KeyEventArgs e)        
{
  if (e.Key == Key.Delete)
  {
    foreach (Order item in historyGrid.SelectedItems)
    {
      history.Remove(item);
    } 
  }
}

But when I hit delete I get that the collection was changed and the enumeration might not work exception


You cannot delete items from a list you are iterating (or in this case a related list).

Create a temporary list of the items you want to delete and iterate that instead.

e.g.

List<Order> itemsToDelete = new List<Order>(historyGrid.SelectedItem);
foreach (Order item in itemsToDelete)
{
    history.Remove(item);
} 

Or as AnthonyWJones rightly suggests, just add a reference to Linq and change your code to

foreach (Order item in historyGrid.SelectedItems.ToList())
{
    history.Remove(item);
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消