Well i got some hard time figuring out what am I doing wrong.
Basically I need to remove Listbox1 items that are less then avarage, but its giving me:
System.ArgumentOutOfRangeException was unhandled
Message=InvalidArgument=Value of ‘9’ is not valid for ‘index’.
Parameter name: 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
Any suggestions?
It is grabbing the max Count at the start of the For/Next Loop and doesn’t reevaluate it. Try iterating backwards that way you are removing from where you have been not from where you are going.
i.e.
From above MSDN Link emphasis mine: