VB listbox cannot be indexed because it has no default value
I have a listbox and I want to loop through each of the items to see if the string im looking for is inside. I know I could do .contains but that wouldnt look at substrings. The code im using looks like this:
While tempInt > Listbox.items.count then
if searchString.contains(listbox(tempInt)) then
end if
tempInt+=1
end while
Everything in the loop is fine but VB gives an error on the listbox(tempInt) part. The error is "class windows.forms.listbox cannot be indexed because it has no default value". Can anyone help get around the default value开发者_如何转开发 crap? I tried putting in a blank string but no change.
Use the Items
property of the listbox, which is accessible via an indexer, like an array...
listBox.Items[0]
The error message means that the ListBox
class does not have an indexer (meaning that it doesn't define a property, known as a default
in VB and an indexer or this
property in C#, which can be passed an index in order to retrieve a value).
You're looking for listbox.Items(tempInt)
Just as an aside, using a For
loop is preferable to the While
you've chosen, though For Each
would probably be best (assuming you don't need the index)
For tempInt as Integer = 0 to listbox.Items.Count - 1
if searchString.contains(listbox.Items(tempInt).ToString()) then
end if
Next
Or, if the index isn't relvant to you, use For Each
For Each item in listbox.Items
if searchString.contains(item.ToString()) then
end if
Next
精彩评论