使用循环删除所有列表框项

时间:2014-02-22 22:42:20

标签: .net vb.net

如何使用循环删除所有列表框项目我还要删除每个位置的所有文件

  For i As Integer = 0 To ListBox1.SelectedIndices.Count - 1
        ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
        ListBox1.SelectedIndex = Me.ListBox1.SelectedIndex + 1
        path1 = folderBrowserDialog1.SelectedPath
        path2 = ListBox1.SelectedItem.ToString
        Dim fullpath As String = My.Computer.FileSystem.CombinePath(path1, path2)
        Kill(fullpath)
    Next

1 个答案:

答案 0 :(得分:5)

循环版本:

For i As Integer = (listbox1.Items.Count - 1) To 0 Step -1
 listbox1.Items.RemoveAt(i)
Next

简单版本:

listbox1.Items.Clear()

仅删除/处理选定的索引:

'get list of selected items
Dim SelectedItems = lsb.SelectedIndices
'collection of indexes to process/remove
Dim sortedSelectedItems As New List(Of Integer)
For Each i In SelectedItems
  sortedSelectedItems.Add(CInt(i))
Next
'sort them from lowest to highest so we remove in correct order
sortedSelectedItems.Sort()
For i = sortedSelectedItems.Count - 1 To 0 Step -1
  Dim file As String = lsb.Items(sortedSelectedItems(i)).ToString
  'do somethign with file
  'remove item
  lsb.Items.RemoveAt(i)
Next