Is it possible to use the "myListBox.contains()" method to identify if a substring is contained in one of the listbox items?
I have a listbox containing a collection of strings (phrases) and would like to know if one of these phrases contains a substring. For example...
myListBox contains the f开发者_高级运维ollowing strings stored in the items collection:
- "The quick brown fox jumps over the lazy dog"
- "One small step for man"
- "Life is like a box of chocolates"
I can successfully identify that a phrase is indeed contained in the listbox.items collection by using:
If myListBox.contains("One small step for man") Then
'do work
End If
However, I would like to identify whether just the substring "small step" is contained in the listbox.items collection.
Is this possible? Perhaps using regular expressions?
You could also use a custom class and override Equals:
Class ListItem
Private _text As String = String.Empty
Public Property Text() As String
Get
Return _text
End Get
Set(ByVal value As String)
_text = value
End Set
End Property
Public Sub New(ByVal text As String)
Me.Text = text
End Sub
Public Overrides Function ToString() As String
Return Me.Text
End Function
Public Overrides Function Equals(ByVal obj As Object) As Boolean
If obj Is Nothing Then
Return False
Else
Return obj.ToString.IndexOf(obj.ToString, StringComparison.CurrentCultureIgnoreCase) > -1
End If
End Function
End Class
Example:
Me.ListBox1.Items.Add(New ListItem("The quick brown fox jumps over the lazy dog"))
Me.ListBox1.Items.Add(New ListItem("One small step for man"))
Me.ListBox1.Items.Add(New ListItem("Life is like a box of chocolates"))
'check with String or another instance of ListItem'
If Me.ListBox1.Items.Contains("small step") Then
'contains substring'
End If
You will have to loop through the collection & test each string.
Just found this, which is what I think I will use...
If myListBox.FindStringExact("small step") <> ListBox.NoMatches Then
Debug.Print("Item was found")
Else
Debug.Print("Item was NOT found")
End If
I don't really need the index of the matching item, otherwise I would make use of the returned integer from the FindStringExact function.
精彩评论