【问题标题】:Visual basic 2010 removing from listbox从列表框中删除 Visual Basic 2010
【发布时间】:2012-05-09 17:12:23
【问题描述】:

好吧,我很难弄清楚我做错了什么。 基本上我需要删除比平均数少的 Listbox1 项目,但它给了我:

System.ArgumentOutOfRangeException 未处理 Message=InvalidArgument='9' 的值对'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

有什么建议吗?

【问题讨论】:

    标签: vb.net vb.net-2010


    【解决方案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 链接强调我的:

    当 For...Next 循环开始时,Visual Basic 计算 start、end 和 步。这是它评估这些值的唯一次。然后它分配 开始反击。在运行语句块之前,它比较 反击结束。如果计数器已经大于最终值(或 如果 step 为负则更小),For 循环结束并且控制传递给 Next 语句之后的语句。否则声明 块运行。

    【讨论】:

    • 是的,这就是问题所在...谢谢!
    【解决方案2】:

    当您删除某个项目时,它不再在列表中,因此列表会变短,并且您的原始计数不再有效。只需递减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
    

    【讨论】:

    • 即使递减 i 我也有同样的错误: System.ArgumentOutOfRangeException 未处理 Message=InvalidArgument=Value of '7' is not valid for 'index'。参数名称:索引
    • 感谢您帮助和简化我的代码!当我更改 For Next 循环时,它现在可以工作了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 2012-02-29
    • 1970-01-01
    相关资源
    最近更新 更多