Reputation: 586
I made a code for delete the selected row, you can see here:
var grid = Players_DataGrid;
var mygrid = Players_DataGrid;
if (grid.SelectedIndex >= 0)
{
for (int i = 0; i <= grid.SelectedItems.Count; i++)
{
mygrid.Items.Remove(grid.SelectedItems[i]);
};
}
grid = mygrid;
But there's a problem. If the user select multiple with ctrl
combination rows the program crash displaying this exception:
Argument out of range exception
on mygrid.Items.Remove(grid.SelectedItems[i]);
Is my code wrong? Isn't the best way to delete values?
Upvotes: 1
Views: 2228
Reputation: 3499
you delete an item from the list you are iterating through. Let's say your list has 10 items so you have an for loop from 0 to 9. If you delete 2 Items you still will iterate to 9 and the list has only 8 items so you get an:
Argument out of range exception
you can solve this by iterating backwards
for (int i = grid.SelectedItems.Count -1; i >= 0; i--)
Edit:
the removed item will be removed from grid.SelectedItems
too.
Upvotes: 2