T1mpp4
T1mpp4

Reputation: 53

VB.NET for each loop not working

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?

Upvotes: 0

Views: 1640

Answers (1)

FloatingKiwi
FloatingKiwi

Reputation: 4506

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.

Upvotes: 2

Related Questions