我有一个列表框,其中包含从使用此代码的txt文件加载的x个对象:
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它加载它们很好。 然后我只尝试像这样循环它们:
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我得到的错误是这样的:
System.Windows.Forms.dll中发生了未处理的“System.InvalidOperationException”类型异常
附加信息:已修改此枚举器绑定的列表。 只有在列表不更改时才能使用枚举器。
我试图手动加载列表框,没有帮助。 有什么帮助吗?
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 TrueIt 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 SubThe 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?
最满意答案
使用
For num = 0 To List.Items.Count - 1 List.SelectedIndex = num Next正如@CodyGray正确地指出的那样:原因是如果你要修改你所枚举的项目集合,就不能使用A for-each循环。
这将最终选择最后一个项目,因此如果您正在为每个项目测试事件处理程序,那么它才真正有用。
Use
For num = 0 To List.Items.Count - 1 List.SelectedIndex = num NextAnd 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.
更多推荐
发布评论