How do I make a search button so I can search for a string in my listbox. Example: The word "Apple" is in the listbox, I type "Apple" into the search box, click search and it shows up with the closest matches.
You'll need to provide a definition of what constitutes "closest". You can't be vague at all when it comes to telling a computer what to do.it shows up with the closest matches
People often ask "can I make a button that does..." like a Button has some special magic. It doesn't. A Button raises a Click event and that's it. That is the sum total of its involvement. If you want to perform an action then you have to write code to perform that action. If you want the action performed when the Button is clicked then you put the code in the Button's Click event handler, but the same code would still perform the same action wherever you put it.
As for the action, the ListBox has FindString and FindStringExact methods that may be useful to you but you've rather muddied the waters by saying:You'll need to provide a definition of what constitutes "closest". You can't be vague at all when it comes to telling a computer what to do.
Dim matches = myListBox.Items.Cast(Of String)().Where(Function(s) s.StartsWith(myTextBox.Text, StringComparison.CurrentCultureIgnoreCase))That presupposes that the items in the ListBox actually are Strings.
There are various ways that could be achieved but, again, your description is rather vague. What do you mean by "it displays"? Do you mean that the other items are removed from the ListBox? Are they to be displayed in a MessageBox? Something else? When posting a question you must remember that we know nothing about what's in your project or what's in your head, so you need to provide us with all the relevant information.
I would suggest something along the lines of what Dunfiddlin suggested, i.e. using a Predicate, but not quite the same implementation. As you're using .NET 4.0, you may as well us a LINQ query, which can be applied directly to the Items of your ListBox. This will give you a list of matching values that you can do with as you will, e.g.Dim matches = myListBox.Items.Cast(Of String)().Where(Function(s) s.StartsWith(myTextBox.Text, StringComparison.CurrentCultureIgnoreCase))That presupposes that the items in the ListBox actually are Strings.
Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
For Each word As String In lstSearch.Items
If word.Substring(0, 2) = txtSearch.Text Then
lstFind.Items.Add(word)
End If
Next
End Sub
Dim matches = myGenericList.Where(Function(s) s.StartsWith(myTextBox.Text, StringComparison.CurrentCultureIgnoreCase))You can then simply bind that to the ListBox:
myListBox.DataSource = matches.ToArray()The ToArray call is required because data-binding requires an IList while matches is only an IEnumerable. Don't worry if that doesn't mean anything to you at present. Just take my word for it.