카테고리 없음

[vb.net] '인덱스가 배열의 범위를 벗어났습니다'오류의 원인은 무엇입니까?

행복을전해요 2021. 2. 19. 16:47

You are constantly replacing the foundItem array when you do founditem = item:

Dim founditem() As String = Nothing
    For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
            Dim item() As String = line.Split(","c)
                    founditem = item
                        Next
                        

Also, you are using (=) the assignment operation instead of (==) relational operator, to compare. Refer to this article for help in understanding the difference between the two.

Instead of this: If stdntyear = founditem(5) And daytoday = founditem(6) Then

Use this: If (stdntyear == founditem(5)) And (daytoday == founditem(6)) Then

Now back to your main error. You continue to assign the itemarray to founditem every time you iterate (Which overwrites previous content). At the end of the Iteration you will be left with the last entry in your CSV only... So in other words, founditem will only have 1 element inside of it. If you try to pick out ANYTHING but index 0, it will throw the exception index was outside the bounds of the array

So when you try to do the following later, it throws the exception.

 Dim stdntfname As String = founditem(3) 'index 3 does not exist! 

To fix it do the following change:

Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
    'NOTE: Make sure you know exactly how many columns your csv has or whatever column
        '      you wish to access. 
            Dim item() As String = line.Split(","c)
                founditem(0) = item(0) 'Assign item index 0 to index 0 of founditem...
                    founditem(1) = item(1)
                        founditem(2) = item(2)
                            founditem(3) = item(3)
                                founditem(4) = item(4)
                                    founditem(5) = item(5) 
                                        founditem(6) = item(6) 
                                        Next
                                        

For more help on how to work with VB.NET Arrays visit this site: http://www.dotnetperls.com/array-vbnet

-------------------

귀하의 라인 Dim item() As String = line.Split(","c)에는 올바른 수의 요소가 존재한다는 보장이 없습니다. 행 중 하나에 쉼표가 누락되었거나 문서에서 빈 후행 행이있을 수 있습니다. If item.Length >= 7올바른 행 수가없는 행 을 추가 하고 건너 뛸 수 있습니다. 또한 VB6과 달리 .Net의 배열은 1 기반이 아닌 0 기반이므로 item (6)이 생각하는 값인지 확인하십시오.



출처
https://stackoverflow.com/questions/22079900