vb.net 在 ListBox 中查找所选项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17218850/
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
Find a selected item in a ListBox
提问by Aaron Hurst
Background: I have a list box that allows multiple selections. There is a specific value in my List Box that, if selected, needs a separate code path to be run for it and all other selections go through another path.
背景:我有一个允许多选的列表框。我的列表框中有一个特定值,如果选中该值,则需要为其运行单独的代码路径,并且所有其他选择都通过另一条路径。
Problem: I can't figure out how to correctly write it in VB.NET to make it work the way I imagine it.
问题:我不知道如何在 VB.NET 中正确编写它以使其按照我想象的方式工作。
Code:
代码:
For Each Item As String In listbox1.SelectedItems
If listbox1.SelectedItem = myValue Then
Do this
Else
Do that
End If
Next
If I make multiple selections on my list the code doesn't work correctly. It only works correctly if myValue is the only selection in listbox1.
如果我在列表中进行多项选择,代码将无法正常工作。只有当 myValue 是 listbox1 中的唯一选择时,它才能正常工作。
Any suggestions?
有什么建议?
回答by Mataniko
Your iteration is wrong, you should use the Item value in your loop:
您的迭代是错误的,您应该在循环中使用 Item 值:
For Each Item As String In listbox1.SelectedItems
If Item = myValue Then
Do this
Else
Do that
End If
Next
A For Each loop basically does the following: (Please excuse any syntax errors, my vb is rusty)
For Each 循环基本上执行以下操作:(请原谅任何语法错误,我的 vb 生疏了)
For index As Integer = 0 To listbox1.SelectedItems.Length
Def Item = listbox1.SelectedItems[index]
Next
回答by The Badak
try:
尝试:
For i = listbox1.Items.Count
If listbox1.Items[i].IsSelected = True Then
'Do this
Else
'Do that
End If
Next i

