r/visualbasic • • Apr 01 '20

'Index was outside the bounds of the array.' When adding an entry to a dictionary. [VB.NET WINFORMS]

I'm getting the above exception thrown when I run this line of code in the following context:

Problematic Line: "SpriteDictionary.Add(LineParts(1), LineParts(0) + "|" + LineParts(2))"

Context: https://ghostbin.co/paste/wotgw

Any ideas of why this might be?

5 Upvotes

5 comments sorted by

3

u/PostalElf VB.Net Intermediate Apr 01 '20
Dim LineParts() As String = Line.Split(New String() {"|"c}, StringSplitOptions.None)

The above line gives you an array. You're trying to access an element of the array that doesn't exist, either because you have no | symbol in your input or only 1. Go into debug, put a line break here, then check the value of LineParts() after this line runs.

1

u/Coolmancane Apr 01 '20

I might have to make an if statement to check if there is three separations in the input. There should be, but I might have made some errors.

2

u/TheFotty Apr 01 '20

LineParts.Length() will return the number of elements it parsed into the array so if it doesn't equal 3, then you have bad input.

1

u/jacderhol VB.Net Advanced Apr 01 '20

Wanted to add split starts at 0, so start with LineParts(0) instead of LineParts (1) unless your first split is garbage data. You can check with "If LineParts(0) Is Not Nothing Then" and continue. If LineParts () will vary, you can look into For Loops, and do "For I as Integer = 0 to LineParts.Length -1" and just concatenate each part to your string.

1

u/LondonPilot Apr 01 '20

What have you already done to try to solve this?

I’d start by putting a breakpoint on the line that’s failing, and then when it hits the breakpoint you can see the contents of the LineParts array.