|
-
April 24th, 2004, 03:19 PM
#1
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
-
April 24th, 2004, 03:36 PM
#2
What is X when you get the error....
TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
2008, 2009,2010
In theory, there is no difference between theory and practice; in practice there is.
* Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions 
* How NOT to post a question here
* Of course you read this carefully before you posted
* Need homework help? Read this first
-
April 24th, 2004, 11:32 PM
#3
it says x = 4 sorry for the late reply, i had to work.
thanks in advance for your help.
-
April 25th, 2004, 03:57 AM
#4
Re: Index out of Range Exception
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.
If I am on the wrong way, Please give me an outspoken criticism.
Fortune favours the bold.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|