EmPlusPlus
EmPlusPlus

Reputation: 181

Delete from ListBox items in a Loop

Each Item information get from a file which specified with the name of that item. Even though the selected items will be deleted properly in the listbox but the file of next item will be deleted. I don't know if problem is for Index or anyother part

  SourceDir  = "c:\"
  For Each itemIndex In listHouse.SelectedIndices()
            itemIndex = listHouse.SelectedIndices(0)
            listHouse.Items.RemoveAt(itemIndex)
            MsgBox(listHouse.Items.Item(itemIndex).Text & "R.txt")
            File.Delete(SourceDir & listHouse.Items.Item(itemIndex).Text & "R.txt")

        Next

Upvotes: 1

Views: 937

Answers (1)

You cannot add or remove items from a collection while inside a For/Each loop.

Each time you RemoveAt(n), you change the make-up of the collection you are looping. If you remove item #4, item 5 moves up to its slot. Then after Next, your code will be looking at position 5, and be looking at what was originally #6 - item 5 would be skipped entirely. To prevent this every-other one bug/issue, an exception is thrown when using a For/Each.

Secondly, your File.Delete code is trying to reference the item you just removed!

To iterate a collection and remove some/all items one by one, loop backwards using an indexer. This removes from the end of the collection so nothing can "move up". Like this:

' loop backwards using For n
For n as Integer = listHouse.SelectedIndices.Count -1 to 0 Step-1
    itemIndex = listHouse.SelectedIndices(n)

    MsgBox(listHouse.Items.Item(n).Text & "R.txt")
    File.Delete(SourceDir & listHouse.Items.Item(n).Text & "R.txt")

    ' also remove the thing AFTER you have used it to delete
    listHouse.Items.RemoveAt(n)
Next

If you tried to use a forward For n loop with this sort of action, you'd get the every-other one issue.

Upvotes: 1

Related Questions