Skip to content

Folder Contents in a Menu

A user on the Xojo Programming forum asked how they might show folder contents in a PopupMenu. Since a PopupMenu is not hierarchical, that wasn’t really an option. But an alternative would be to show the contents in a hierarchical menu.

Here’s how you can recurse through files and add them to a regular MenuItem:

Private Function CreateFolderMenu(f As FolderItem) as MenuItem
  Var base As New MenuItem(f.Name, f)
  For Each child As FolderItem In f.Children
    If child.IsFolder Then
      Var m As New MenuItem(child.Name, child)
    End If

  Return base
End Function

You can call it like this:

Var startFolder As FolderItem = SpecialFolder.Documents
FolderMenu = CreateFolderMenu(startFolder) // Property FolderMenu As MenuItem

And show the menu like this:

Var selectedFile As MenuItem = FolderMenu.Popup

If selectedFile <> Nil Then
  Label1.Text = FolderItem(selectedFile.Tag).NativePath
End If

Sample project download

Another alternative might be to show the folder in a hierarchical ListBox. An example project for that is included with the Xojo download: Examples/Files/FileBrowser