Visual Basic 2010从列表框中删除

时间:2012-04-29 21:48:34

标签: vb.net vb.net-2010

我很难搞清楚自己做错了什么。 基本上我需要删除不那么平均的Listbox1项目,但它给了我:

System.ArgumentOutOfRangeException未处理   Message = InvalidArgument ='9'的值对'index'无效。 参数名称:index

Private Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.Click
    Dim Myrand As New Random
    Dim res As Double
    Dim i As Integer
    Dim n As Integer
    Dim tot As Double
    Dim avarage As Double

    ListBox1.Items.Clear()

    For i = 0 To 14 Step 1
        res = Math.Round(Myrand.NextDouble, 3)
        ListBox1.Items.Add(res)
        tot = tot + res
    Next

    avarage = tot / ListBox1.Items.Count
    MsgBox(avarage)

    For i = 0 To ListBox1.Items.Count - 1 Step 1
        If ListBox1.Items(i) < avarage Then
            ListBox1.Items.RemoveAt(i)
            n = n + 1
        End If
    Next

    MsgBox("Removed " & n & " items!")
End Sub

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

当您删除某个项目时,它不再在列表中,因此列表会变短,原始计数不再有效。只需递减i

Private Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.Click
    Dim Myrand As New Random
    Dim res As Double
    Dim i As Integer
    Dim n As Integer
    Dim tot As Double
    Dim avarage As Double

    ListBox1.Items.Clear()

    For i = 0 To 14
        res = Math.Round(Myrand.NextDouble, 3)
        ListBox1.Items.Add(res)
        tot += res
    Next

    avarage = tot / ListBox1.Items.Count
    MsgBox(avarage)

    For i = 0 To ListBox1.Items.Count - 1
        If ListBox1.Items(i) < avarage Then
            ListBox1.Items.RemoveAt(i)
            i -= 1
            n += 1
        End If
    Next

    MsgBox("Removed " & n & " items!")
End Sub

答案 1 :(得分:1)

它抓取For / Next循环开始时的最大计数和doesn't reevaluate it。尝试向后迭代,这样你就可以从你去过的地方移开。

For i = ListBox1.Items.Count - 1 To 0 Step -1
    If ListBox1.Items(i) < avarage Then
        ListBox1.Items.RemoveAt(i)
        n = n + 1
    End If
Next

从上面的MSDN Link强调我的:

  

当For ... Next循环启动时,Visual Basic会评估start,end和   步。这是评估这些值的唯一时间。然后分配   开始反击。在运行语句块之前,它会进行比较   反对结束。如果计数器已经大于结束值(或   如果step为负,则更小,For循环结束,控制传递到   Next语句后面的语句。否则声明   阻止运行。

相关问题