Tim Tim - 3 years ago 177
Vb.net Question

.NET Delete multiple files from list box

I would like to delete multiple selected files from list box, however only one file is deleted when multiple items are selected.

The code are as below

Dim dialog As DialogResult
dialog = MsgBox("Delete Forever?", MsgBoxStyle.YesNoCancel)

If dialog = MsgBoxResult.Yes Then
For i As Integer = (ListBox1.SelectedItems.Count - 1) To 0 Step -1
FileSystem.DeleteFile(ListBox1.Items(ListBox1.SelectedIndex).ToString(), UIOption.AllDialogs, RecycleOption.DeletePermanently)
ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
Next
Else
MessageBox.Show("Not Deleted!")
End If


I do believe that the for loop is not in the correct form.

Answer Source

Easy thing first, check that something is selected before hand. This'll simply your code for nesting a bit and I find it keeps me focused on what things I need to pay attention to.

Next, it'll probably be easier to iterate over the selected items, not by selected index. Meaning something like this (this is pseudocode, so it might not actually compile)

For Each item In ListBox1.SelectedItems
   FileSystem.DeleteFile(item.ToString(), UIOption.AllDialogs, RecycleOption.DeletePermanently)
   ListBox1.Items.Remove(item)
Next

So bringing these things all together, that'll change your code into something like this (also pseudocode, not checked)

If ListBox1.SelectedItems.Count = 0 Then
    MessageBox.Show("Nothing Selected!")
End If

Dim dialog As DialogResult
dialog = MsgBox("Delete Forever?", MsgBoxStyle.YesNoCancel)
If dialog <> MsgBoxResult.Yes Then Return

For Each item In ListBox1.SelectedItems
   FileSystem.DeleteFile(item.ToString(), UIOption.AllDialogs, RecycleOption.DeletePermanently)
   ListBox1.Items.Remove(item)
Next
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download