每个循环的VB.NET都不起作用(VB.NET for each loop not working)

编程入门 行业动态 更新时间:2024-10-26 19:29:32
每个循环的VB.NET都不起作用(VB.NET for each loop not working)

我有一个列表框,其中包含从使用此代码的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 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?

最满意答案

使用

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 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.

更多推荐

本文发布于:2023-07-20 12:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1199628.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:都不   NET   VB   loop   working

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!