Contextual Menu Help

I am working on a contextual menu and I have code to delete files but all the files except for the last one get deleted. Can someone help me? My code is below:

Elseif selectedItem.Text = "Delete Selected Item(s)" Then
  
  If lbxFiles.RowSelectedAt(xx) Then
    
    Var file As FolderItem
    file = New FolderItem(lbxFiles.CellTextAt(lbxFiles.SelectedRowIndex, 2).ToText, FolderItem.PathModes.Native)
    
    file.Delete
    lbxFiles.RemoveRowAt(xx)
    lbxFiles.Refresh
    
  End if
  
End if

If you want to delete multiple files based on whether row(s) are selected in your listbox then you will want to put a loop in the method and process the listbox from bottom to top. In your code you are mixing multiple selection (RowSelectedAt) and single selection (SelectedRowIndex) functionality.

Something like this should work (coded here)

For i As Integer = lbxFiles.LastRowIndex DownTo 0
  If lbxFiles.RowSelectedAt(i) Then
    Var file As New FolderItem(lbxFiles.CellValueAt(i, 2), FolderItem.PathModes.Native)
    file.Remove
    lbxFiles.RemoveRowAt(i)
  End If
Next i

I’m assuming you’ve not included Folders in your list, but if you have you’ll need to handle removal of children before removing the folder.

HTH

Wayne

2 Likes

You also want to check that the file is not nil and exists before trying to delete, er, “remove” it, and you need a Try-Catch to catch IO Exceptions in case anything goes wrong (e.g. file busy or locked).

1 Like

Thanks Wayne and Julia. Your version of the script worked great and I am building in the Try-Catch statement today.

I really dislike Xojo’s new approach of using exceptions for everything, necessitating Try-Catch everywhere. It was so much more convenient to just check a LastError property.

2 Likes