Index was outside the bounds of the array.

Johnson

Well-known member
Joined
Mar 6, 2009
Messages
158
Programming Experience
Beginner
I cant seem to see what is wrong with this arrary size. It works if i set the random number to 10

pretty sure it's to do with this line For i = 0 To intResult but i cant for the life of me figure it out.

VB.NET:
        Dim intResult As Integer
        '// Initializes the random-number generator, otherwise each time you run your
        '// program, the sequence of numbers will be the same
        Randomize()
        intResult = Int((100 * Rnd()) + 1) '// Generate random value between 1 and 100.

        '//Add the new random list of directorys to listbox
        Dim sDirs() As String
        Dim i As Integer = 1

        sDirs = System.IO.Directory.GetDirectories("c:\")

        For i = 0 To intResult
            lstDirectorys.Items.Add(sDirs(i))
        Next

        '//Set the last directory as a varible
        Dim strLastDir As String = ""
        strLastDir = sDirs(lstDirectorys.Items.Count - 1)
 
Since your index is starting with zero, your max in your loop should actually be one less that the total count

For i = 0 to (intResult -1)
 
have you stepped thru the code to see what value is in intResult? I dont see any reason why it wouldnt enter the loop as long as you have a value in that variable and actual items in your array.
 
this line was flagged lstDirectorys.Items.Add(sDirs(i))

indexoutofrangeexception was unhandled

Index was outside the bounds of the array.
 
What's the value of i when it crashes?

Your loop is:
VB.NET:
        For i = 0 To intResult
            lstDirectorys.Items.Add(sDirs(i))
        Next
and the value of intResult is:
VB.NET:
intResult = Int((100 * Rnd()) + 1) '// Generate random value between 1 and 100.
Which means it's giving you a number that's too high for the array, hence the out of bounds exception.
 
Hmm i think i could of psotetd the problem.

Basically what i am doing is i want to select a random dir from the c drive.

It seems to crash at any number roughly over 10.

There are 13 dirs in the c drive.

could this be crashing because it's creating an array of 13 folders and giving a number over this?

is there a better way to select a random dir?
 
What your doing is pretty good, just got to make sure that the random number doesn't exceed the amount of items in the sDirs array.
 
Back
Top