Click to See Complete Forum and Search --> : Index out of Range Exception


donlab
April 24th, 2004, 03:19 PM
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

TheCPUWizard
April 24th, 2004, 03:36 PM
What is X when you get the error....

donlab
April 24th, 2004, 11:32 PM
it says x = 4 sorry for the late reply, i had to work.
thanks in advance for your help.

vnInformatics
April 25th, 2004, 03:57 AM
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)


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.