Search code examples
c#wpfobservablecollectiondelete-row

The deletion of one row from an ObservableCollection fails in grid


The deletion of one row in my grid causes an error called "System.InvalidOperationException".

The row is successfully being deleted in my database but when the grid udates my observable collection the above mentioned error occurs.

Here is my code:

UserControlStaff.xaml.cs

private void deleteUserData_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Delete)
        {
            var grid = (DataGrid)sender;
            if (grid.SelectedItems.Count > 0)
            {
                var Res = MessageBox.Show("Are you sure you want to delete " + grid.SelectedItems.Count + " Users?", "Deleting Records", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                if (Res == MessageBoxResult.Yes)
                {
                    try
                    {
                        string connectionString = ConfigurationManager.ConnectionStrings["MyApp.Properties.Settings.ConString"].ConnectionString;
                        string queryString = string.Empty;

                        using (SqlConnection connection = new SqlConnection(connectionString))
                        {

                            foreach (var row in grid.SelectedItems)
                            {
                                User user = row as User;

                                queryString = "DELETE FROM Users WHERE ID = " + user.ID;
                                SqlCommand cmd = new SqlCommand(queryString, connection);
                                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                                DataTable dt = new DataTable("Users");
                                sda.Fill(dt);

                                mUserDataObject.Remove(user);
                            }

                        }
                    }
                    catch
                    {
                        throw;
                    }

                    MessageBox.Show(grid.SelectedItems.Count + " Users have being deleted!");
                }
            }
        }
    }

Solution

  • Collection can't be modified while you are enumerating over the collection.

    Create a new instance of list if you want to remove the item:

    foreach (var row in grid.SelectedItems.OfType<User>().ToList())
    {
       ...
       mUserDataObject.Remove(user);
    }
    

    Make sure to add System.Linq namespace to use extensions methods.