2017-10-01 8 views
0

複数の選択ファイルをリストボックスから削除しますが、複数のアイテムが選択されている場合は1つのファイルのみが削除されます。.NET複数のファイルをリストボックスから削除する

コードは、私がforループが正しい形式ではないことを信じていないよう

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 

下回っています。

答えて

1

まず、簡単に何かが手前で選択されていることを確認します。これはちょっと入れ子にするためのコードに過ぎず、注意を払う必要があるものに焦点を当てています。

次に、選択したインデックスではなく、選択したアイテムを繰り返し処理する方が簡単でしょう。

この(それは実際にはコンパイルされない場合がありますので、これは、擬似コードである)

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

だから、すべて一緒にこれらの事を持って来るようなものを意味、それは(チェックされていないにも擬似コード、)このような何かにあなたのコードを変更します

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 
+1

ありがとうございます! https://stackoverflow.com/questions/18947629/list-that-this-enumerator-is-bound-to-has-been-modifiedで動作するように管理されています – Tim

関連する問題