Index out of Range Exception
greetigs,
im trying to load data from a .txt file into an array, and print. but whenever i debugg this lil bit of code, keep getting and error. any ideas?
[CODE] Public item(3) As Integer
Public itemname(3) As String
Public price(3) As Double
Public frm1 As String = "{0,-8}{1,-20}{2,6:c2}"
Public x As Integer
Private Sub btn1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn1.Click
Dim sr As IO.StreamReader = IO.File.OpenText("food.txt")
Do While sr.Peek <> -1
x += 1
item(x) = sr.ReadLine
itemname(x) = sr.ReadLine
price(x) = sr.ReadLine
lst1.Items.Add(String.Format(frm1, item(x), itemname(x), price(x)))
Loop
sr.Close()
End Sub
Re: Index out of Range Exception
Quote:
Originally posted by donlab
..............................
Public itemname(3) As String
From this declaration, We can easily to see that ...the Maximum number of elements is 4( the index is from 0 -> 3)
Quote:
Private Sub btn1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn1.Click
Dim sr As IO.StreamReader = IO.File.OpenText("food.txt")
Do While sr.Peek <> -1
x += 1
item(x) = sr.ReadLine
itemname(x) = sr.ReadLine
price(x) = sr.ReadLine
lst1.Items.Add(String.Format(frm1, item(x), itemname(x), price(x)))
Loop
sr.Close()
End Sub
In this source-code, Easily to see that you havenot yet checked the index of the Item array, I mean the value of x what is index of the array.
That is why you will get the error at the value of x = 4.
Hope in this help.