简体   繁体   中英

Index was outside the bounds of the array - VB2008

Why am i keep on getting this error: Index was outside the bounds of the array. Please help. Thank you.

 Dim list As New ListBox
 Dim dirsize As Integer
 Dim a As Integer
 Dim container(0) As String

 Dim counter As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
 counter = My.Computer.FileSystem.GetFiles("C:\myfolder")
 dirsize = counter.Count

 For a = 0 To dirsize

     container(a) = a + 1
     lstItems.Items.Add(container(a))

 Next

Basically container has only 1 element which you dim at the beginning of your sub. You never resize container, so if dirsize is anything else than 0 you will get this error.

You should do something like:

 Dim list As New ListBox
 Dim dirsize As Integer
 Dim a As Integer
 Dim container() As String

 Dim counter As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
 counter = My.Computer.FileSystem.GetFiles("C:\myfolder")
 dirsize = counter.Count

 **ReDIm container(dirsize)**
 For a = 0 To dirsize

     container(a) = a + 1
     lstItems.Items.Add(container(a))

 Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM