Background: I am building a database application to store information about my massive movie collection. The listbox contains hundreds of items so I decided to implement a search feature which would highlight all items that contain a particular string. Sometimes it's hard to remember an entire movie title so I thought this would come in handy.
I found this useful code on the Microsoft site that highlights all items in a listbox that contain a particular string. How can I modify it to search through each string entirely?
Currently the code only searches for items that start with the search string, instead of seeing if it contains the search string anywhere else. I came across a listbox.items.contains() kind of method on Google, although I have no idea how to convert my code for it.
http://forums.asp.net/t/1094277.aspx/1
private void FindAllOfMyString(string searchString)
{
// Set the SelectionMode property of the ListBox to select multiple items.
listBox1.SelectionMode = SelectionMode.MultiExtended;
// Set our intial index variable to -1.
int x =-1;
// If the search string is empty exit.
if (searchString.Length != 0)
{
// Loop through and find each item that matches the search string.
do
{
// Retrieve the item based on the previous index found. Starts with -1 which searches start.
x = listBox1.FindString(searchString, x);
// If no item is found that matches exit.
if (x != -1)
{
// Since the FindString loops infinitely, determine if we found first item again and exit.
if (listBox1.SelectedIndices.Count > 0)
{
if(x == listBox1.SelectedIndices[0])
return;
}
// Select the item in the ListBox once it is found.
listBox1.SetSelected(x,true);
}
}while(x != -1);
}
}
Create your own search function, something along the lines of
(beware, I wrote this out of my head without compiling or testing, the code may contain bugs, but I think you will get the idea!!!)
just one liner
:) Regards
Use String.IndexOf for a case-insenstive string search on each item in your ListBox:
I also suggest they you set your ListBox's SelectionMode property in the Winform designer, or in your forms constructor method.
Same question was asked: Search a ListBox and Select result in C#
I propose another solution:
Not good for listbox > 1000 items.
Each iteration loops all items.
Finds and stays on most suitable case.
Hope this help!
What about the below. You just need to improve it a bit
I'm not sure about the code you posted, but I wrote a small method to do what you're looking for. It's extremely simple: