从列表框中删除数组中包含的项时出错

时间:2014-01-31 22:03:21

标签: vb.net listbox treeview

我正在尝试从列表框中清除当前在树视图中显示为子节点的项目。我已经想出将子节点存储在一个数组中(这是有效的)然后认为我会循环并删除列表框项目(如果它出现在数组中)(基本上是通过双击树视图添加treenodes并放置在约会父节点)。

当我运行代码时,我在最终的Next

上收到以下错误消息

List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.

我知道这与For Each循环有关,但我正在努力解决这个问题。

Dim ndes As New ArrayList
Dim no As TreeNode
    For Each no In tvProgress.Nodes

        Dim CNode As TreeNode
        For Each CNode In no.Nodes
            ndes.Add(CNode.Text)
        Next
    Next

    Dim ditem As Object

    For Each ditem In lstPlanned.Items
        If ndes.Contains(ditem) Then
            lstPlanned.Items.Remove(ditem)
        End If
    Next

1 个答案:

答案 0 :(得分:1)

你需要一个差异循环:

For i As Integer = (lstPlanned.Items.Count - 1) To 0 Step -1
    If ndes.Contains(lstPlanned.Items(i)) Then
        lstPlanned.Items.Remove(lstPlanned.Items(i))
        Exit For
    End If
Next