Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

PowerShell GUI Listbox - .Remove/.RemoveAt - An error occurred while enumerating through a collection: List that this enumerator is bound to has been modified. ...

$
0
0

I have two listboxes:  one that contains a whole bunch of mailboxes, and the other that has the "selected mailboxes" with a ">>" and "<<" button in between them.  The adding part of one to the other works perfectly but the removal throws the following error:

An error occurred while enumerating through a collection: List that this enumerator is bound to has been modified. An e
numerator can only be used if the list does not change..
At C:\Users\me\Desktop\my_Tool.ps1:636 char:11
+             foreach <<<<  ($mailbox in $colMailboxes) {
    + CategoryInfo          : InvalidOperation: (System.Windows....EntryEnumerator:EntryEnumerator) [], RuntimeExcepti
   on
    + FullyQualifiedErrorId : BadEnumeration

I even tried assigning the listbox contents to another object collection but that didnt' resolve the problem.  My actual code throwing the error is below:

$button1_Click={
 if ($listbox1.SelectedItems.Count -gt 0) {
  [void] $listbox2.Items.AddRange($listbox1.SelectedItems) <--- works
  
  [object] $colMailboxes = $listbox1.SelectedItems
  foreach ($mailbox in $colMailboxes) {
   $listbox1.Items.Remove($mailbox) <--- Line throwing the error
  }
 }
}


Edit:  Additional Info:  The above code actually removes the FIRST selection in the list, but on the next selection is when it throws the error...

Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>