none
C# - Compare listboxes - remove listbox item from listbox1 if it does not exist in listbox2

    Question

  • I'm trying to use the below but it's spitting out an error and won't work.

    The error I'm receiving is:

    An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

    Additional information: List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.

               

                foreach (string i in listbox1.Items)
                {
                    if (!listbox2.Items.Contains(i))
                    {
                        listbox1.Items.Remove(i);
                    }
                }

    Any help would be greatly appreciated.

    Thanks

    Saturday, May 10, 2014 5:26 PM