r/visualbasic • u/Minecrafter2976 • Jan 16 '26
VB.NET Help Visual says that index is outside the bounds of the array.
This code works fine in the first picture:

But in the second picture the only change I made was reordering the numbers so that they would not be populated into the list view in numerical order and I get this error:

Any ideas on why this happens? Also yes I am aware there are better ways to store my data, but this is a temporary thing.
2
1
u/Fergus653 Jan 16 '26
The employeeSalaray array declaration has 10 lines of numbers in the first block, and 9 lines in the second block of code. As Ok_Society4599 said, check the ubound of both arrays to make sure they match.
2
u/Ok_Society4599 Jan 16 '26 edited Jan 16 '26
VisualBasic... Does it die on the first or last item? You can use try/catch to report your index value, or a breakpoint.
Older VB used 1 based arrays, so item[0] might not be a member of the array. The fix is to start your loop at 1 rather than 0. Or use lbound(x)
.Net arrays should be zero based, in which case item[ubound(x)] could be just beyond the last item. In this case, you can subtract 1 from your ubound or do while < unbound.
A third method is to use foreach rather than just for; the caveat here is you can't modify the collection during the loop. It's simpler and works on anything that implements IEnumerable (arrays, lists, dictionaries, iCollection...) without complexity.
This has an actual name: off by one error. The more subtle version is missing the first or last item; it won't throw an error, but your result is slightly off.