Adam Kim Adam Kim - 25 days ago 8
C# Question

search string inside string

I'm working on application that's need search method I have listbox full with items every item have singer name and song title , I need be able to search the song title or singer name on same method that's what's I tried so far :

public void search_song()
{

for (int i = listbox_titles.Items.Count - 1; i >= 0; i--)
{
int char_count = listbox_titles.Items[i].ToString().Length;
if (listbox_titles.Items[i].ToString().ToLower().Contains(txt_to_search.Text) || listbox_titles.Items[i].ToString().StartsWith(txt_to_search.Text, StringComparison.Ordinal) || listbox_titles.Items[i].ToString().ToLower().Substring(0, char_count).Contains(txt_to_search.Text)) ;
{
//listbox_titles.SetSelected(i, true);
MessageBox.Show(listbox_titles.Items[i].ToString());
}
}


its work but only search from the beginning of items not middle
any ideas ??

this example of what's I want if item is **avicii waiting for love ** if I search waiting for love is should give me the item .

Answer Source

You just need to find the list box item that contains what you search for, so you don't need for StartsWith method, but since you're saying that your search method only works on the starting string, I can find that you're not converting the text to lower in StartsWith as in Contains, and that might what make the issue. So if your check is case insensitive you can just use the following:

  public void search_song()
        {

            for (int i = listbox_titles.Items.Count - 1; i >= 0; i--)
            {
                int char_count = listbox_titles.Items[i].ToString().Length;
                if (listbox_titles.Items[i].ToString().IndexOf(txt_to_search.Text, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    //listbox_titles.SetSelected(i, true);
                    MessageBox.Show(listbox_titles.Items[i].ToString());
                }
            }