0

I have a listbox that has x amount of object loaded from a txt file with this code:

 Dim lines() As String = IO.File.ReadAllLines(Application.StartupPath() + "\file.txt") List.Items.AddRange(lines) Try List.SelectedIndex = 0 Catch ex As Exception End Try Return True 

It loads them fine. Then I only try to loop through them like this:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim num As Integer = 0 Dim item As Object For Each item In List.Items List.SelectedIndex = num num += 1 Next End Sub 

The error I get is this:

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.

I tried to load the listbox manually, didn't help. Any help here?

5
  • 1
    What are you trying to accomplish with that loop? Commented Aug 15, 2016 at 15:09
  • Only to change the selected index. @Fairy Commented Aug 15, 2016 at 15:10
  • Never use an empty try-catch. It hides problems. Commented Aug 15, 2016 at 15:14
  • 2
    But why loop it? Whats the point? Do you want to go trough every item and select it? Commented Aug 15, 2016 at 15:15
  • Yes. The point is to go through each item. Later I can then add something with it @Fairy Commented Aug 15, 2016 at 15:16

1 Answer 1

2

Use

 For num = 0 To List.Items.Count - 1 List.SelectedIndex = num Next 

And as @CodyGray rightly pointed out: The reason for this is A for-each loop cannot be used if you're going to modify the collection of items you're enumerating over.

This will end up with the last item selected so it's only really of any use if you're testing out your event handlers for every item.

Sign up to request clarification or add additional context in comments.

1 Comment

You should explain why you have to do this. In other words, why your solution fixes the problem. (A for-each loop cannot be used if you're going to modify the collection of items you're enumerating over.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.