Vb.net 确保listbox和collection都从同一点(0或1)开始

Vb.net 确保listbox和collection都从同一点(0或1)开始,vb.net,Vb.net,我在按钮单击事件中有以下代码: If myCollection.Count > 0 Then Dim curItemIndex As Integer = myListbox.SelectedIndex If myCollection.Item(curItemIndex) IsNot Nothing Then myCollection.Remove(curItemIndex) MessageBox.Sho

我在按钮单击事件中有以下代码:

    If myCollection.Count > 0 Then
        Dim curItemIndex As Integer = myListbox.SelectedIndex
        If myCollection.Item(curItemIndex) IsNot Nothing Then
            myCollection.Remove(curItemIndex)
            MessageBox.Show("Address removed!")
        Else
            MessageBox.Show("Could not delete entry!")
        End If
    Else
        MessageBox.Show("Address book is empty!")
    End If
当我向集合中添加项目,然后尝试将其删除时,总是会出现以下错误:

System.IndexOutOfRangeException:'集合索引必须位于 范围1到集合的大小。”

当我逐步通过调试器时,我看到:

  • myCollection.Count=1

  • SelectedIndex=0

  • curItemIndex=0

因此,我不明白为什么列表框中当前选定的项表示集合从1开始时为0

如何修复此问题,使两者都从0开始


谢谢

这似乎是一个基于VB的集合。按照Microsoft的建议浏览System.Collections.Generic命名空间。如果集合都是相同的数据类型,则最简单的类之一是List(of T)。然后列表框索引和列表索引应该匹配(都是从零开始的)。要使它们保持同步,请确保也从列表框中删除该项目。

如果继续使用
集合
,则
如果myCollection.item(curItemIndex+1)不是空,则
myCollection.remove(curItemIndex+1)
。但是您应该使用
列表
,并将ListView绑定到它。