在For Each中获取当前元素

时间:2018-08-31 17:38:37

标签: vb.net

我正在尝试获取For Each正在执行的当前元素,但是我正在

  

InvalidOperationException:与枚举器关联的列表已被修改。仅当列表保持不变时,才能使用枚举器。

那是代码:

For Each i As String In ListBox1.Items
    Try
        [..code]
    Catch ex As WebException
        If ex.Status = WebExceptionStatus.ProtocolError Then
            Dim Risposta As DialogResult
            Risposta = MessageBox.Show(String.Format("Errore: Impossibile trovare l'SWF {0}. Continuare?", i), "Errore durante il check degli SWF!", MessageBoxButtons.YesNo)
            If Risposta = System.Windows.Forms.DialogResult.Yes Then
                ListBox1.Items.Remove(i) <- Thats where the error pops up
            End If
            If Risposta = System.Windows.Forms.DialogResult.No Then
                Application.Exit()
            End If
        Else
            MessageBox.Show(String.Format("Errore: {0}", ex.Message), "Errore sconosciuto durante il check degli SWF!")
            Application.Exit()
        End If
    End Try

我该如何解决?

2 个答案:

答案 0 :(得分:1)

您不能修改迭代器,因此必须使用常规的for循环。

For i as Integer = ListBox1.Items.Count() - 1 To 0 Step -1
    ListBox1.Items(i)          //to access
    ListBox1.Items.RemoveAt(i) //to remove
Next

添加了注释中的代码修复

答案 1 :(得分:1)

一种可能的解决方案是存储要删除的项目,然后在遍历ListBox项目之后将其删除,如下所示:

Sub RemoveImpossible(itemsToRemove As List(Of String))
    For Each s In itemsToRemove
        ListBox1.Items.Remove(s)
    Next

End Sub

Sub X()
    Dim impossibleItems As New List(Of String)

    For Each i As String In ListBox1.Items
        Try
            ' [..code]
        Catch ex As WebException
            If ex.Status = WebExceptionStatus.ProtocolError Then
                Dim Risposta As DialogResult
                Risposta = MessageBox.Show(String.Format("Errore: Impossibile trovare l'SWF {0}. Continuare?", i), "Errore durante il check degli SWF!", MessageBoxButtons.YesNo)
                If Risposta = System.Windows.Forms.DialogResult.Yes Then
                    impossibleItems.Add(i)
                End If
                If Risposta = System.Windows.Forms.DialogResult.No Then
                    Application.Exit()
                End If
            Else
                MessageBox.Show(String.Format("Errore: {0}", ex.Message), "Errore sconosciuto durante il check degli SWF!")
                Application.Exit()
            End If
        End Try
    Next

    RemoveImpossible(impossibleItems)

End Sub

这样,如果那是有用的事,那么以后可以对不起作用的项目进行其他处理。