Ryan
Ryan

Reputation: 5546

silverlight delete row with delete key

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

Upvotes: 2

Views: 2269

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93601

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

Upvotes: 3

Related Questions