CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2004
    Posts
    2

    Angry 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

  2. #2
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125
    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

  3. #3
    Join Date
    Apr 2004
    Posts
    2
    it says x = 4 sorry for the late reply, i had to work.
    thanks in advance for your help.

  4. #4
    Join Date
    Oct 2003
    Location
    C/C++,Java,VB.net
    Posts
    43

    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
  •  





Click Here to Expand Forum to Full Width

Featured