Search code examples
c#wpfdatagridselecteditem

WPF DataGrid Remove SelectedItems


Recently I've been working on a project which imports data programmicaly into a WPF DataGrid.

I'm almost done with the project but the thing that I left out was a button to remove selected cells and this is where I'm stuck!

I wrote this code using my basic knowledge of DataGrids:

var grid = dataGrid1;
if (grid.SelectedIndex >= 0)
 {
   for (int i = 0; i <= grid.SelectedItems.Count; i++)
   {
      grid.Items.Remove(grid.SelectedItems[i]);
   };
 }

Works fine on removing only the item selected just like CurrentItem but it doesn't remove anymore than 2 selected items!

The DataGrid I have should at least contain a minimum of 100 items. I've added a remove all option but this is also necessary.

I'll be thankful if anyone gives me the solution.


Solution

  • By removing selected item you are changing SelectedItems collection. You should copy it first and then start removing.