1

I'm populating a hierarchical listbox with folders and files. I fill my listbox with these lines of code:

  For i As Integer = 1 To General.GetBlocksFolder.count
    If General.GetBlocksFolder.Item(i).Directory Then
       frmMain.BlockList.Append(General.GetBlocksFolder.Item(i).DisplayName, True)
       frmMain.BlockList.RowTag(i-1) = General.GetBlocksFolder.Item(i).GetSaveInfo(GetFolderItem(""))
    End if
  Next

General.GetBlocksFolder is an object that holds info over a folder on my system. BlockList is a list to show 'blocks' in my program. This works as expected, I see the folders inside that list.

Then, when I expand a row, I use following code:

  Dim ItemsAdded as integer
  Dim CurrentFolder As FolderItem = General.GetBlocksFolder.GetRelative(me.RowTag(row))

  For i As Integer = 1 To CurrentFolder.count
    ItemsAdded = ItemsAdded +1 
    If CurrentFolder.Item(i).Directory Then
      frmMain.BlockList.Append(CurrentFolder.Item(i).DisplayName, True)
      frmMain.BlockList.RowTag(i+ItemsAdded) = CurrentFolder.Item(i).GetSaveInfo(GetFolderItem(""))
    Else
      frmMain.BlockList.Append(CurrentFolder.Item(i).DisplayName)
    End if
  Next

This works nicely, but when I go deeper then 3 levels, I get an error. A nilObjectException on 'CurrentRow'

Anybody knows what kind of sorcery this is?

Thanks in advance Mathias

Paul Lefebvre
  • 6,253
  • 3
  • 28
  • 36
Mathias Maes
  • 461
  • 1
  • 6
  • 17

1 Answers1

2

You must consider that Item() returns nil. This is the case if files get deleted while you're in the loop, for instance, or when you encounter items that are not accessible due to being of a special type or because of missing permissions.

Therefore, assign CurrentFolder.Item(i) first to a variable and test if it's nil before using it further, like this:

for i as integer = 1 to dir.count
  dim f as folderitem = dir.trueitem(i)
  if f = nil then continue // skip inaccessible items
  addrow ...
next

Also, you have a design mistake in your code:

You should use the TrueItem() function, not Item(). Otherwise, you could end up in an endless loop when going deeper, encountering a symbolic link or Mac Finder alias.

Thomas Tempelmann
  • 11,045
  • 8
  • 74
  • 149