vb.net 如何从列表框中删除选定的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41988826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove selected items from a listbox
提问by marky
This is for a VB.NET 4.5 project in VS2015 Community.
这是针对 VS2015 社区中的 VB.NET 4.5 项目。
I am trying to remove certain selected items from a listbox, but only if the selected item meets a condition. I've found plenty of examples on how to remove selected items. But nothing that works with a condition nested in the loop going through the selected items (at least, I can't get the examples to work with what I'm trying to do...)
我试图从列表框中删除某些选定的项目,但前提是选定的项目满足条件。我找到了很多关于如何删除所选项目的示例。但是对于嵌套在循环中遍历所选项目的条件没有任何作用(至少,我无法让示例与我正在尝试做的事情一起工作......)
Here's my code:
这是我的代码:
Dim somecondition As Boolean = True
Dim folder As String
For i As Integer = 0 To lstBoxFoldersBackingUp.SelectedItems.Count - 1
If somecondition = True Then
folder = lstBoxFoldersBackingUp.SelectedItems.Item(i)
Console.WriteLine("folder: " & folder)
lstBoxFoldersBackingUp.SelectedItems.Remove(lstBoxFoldersBackingUp.SelectedItems.Item(i))
End If
Next
The console output correctly shows the text for the current iteration's item, but I can't get the Remove() to work. As the code is now, I get the console output, but the listbox doesn't change.
控制台输出正确显示当前迭代项目的文本,但我无法让 Remove() 工作。就像现在的代码一样,我得到了控制台输出,但列表框没有改变。
回答by LarsTech
Removing items changes the index position of the items. Lots of ways around this, but from your code, try iterating backwards to avoid that problem. You should also remove the item from the Items collection, not the SelectedItems collection:
删除项目会更改项目的索引位置。有很多方法可以解决这个问题,但是从您的代码中,尝试向后迭代以避免该问题。您还应该从 Items 集合中删除该项目,而不是 SelectedItems 集合:
For i As Integer = lstBoxFoldersBackingUp.SelectedItems.Count - 1 To 0 Step -1
If somecondition = True Then
folder = lstBoxFoldersBackingUp.SelectedItems.Item(i)
Console.WriteLine("folder: " & folder)
lstBoxFoldersBackingUp.Items.Remove(lstBoxFoldersBackingUp.SelectedItems(i))
End If
Next
回答by Robert mbulanga
You can simply use this in order to remove a selected item from the listbox ListBox1.Items.Remove(ListBox1.SelectedItem)
您可以简单地使用它来从列表框 ListBox1.Items.Remove(ListBox1.SelectedItem) 中删除选定的项目
I hope this was helpful.
我希望这可以帮到你。

