简体   繁体   中英

c# listbox live search

I am learning c# and I started by making some dummy app, with all elements I can practice in it. I have search text field and below I have a list box with items.

I tried with this code but I got result only if I start searching from the first letter. I want to be able to search by letters in between words.

Example: List Item: "0445110085" If I start searching from "0445" I will get results but id I start with "5110" for example I got message item not found.

Below is my code,

private void searchBox_TextChanged(object sender, EventArgs e)
    {
        string myString = searchBox.Text;
        int index = listBox1.FindString(myString, -1);
        if (index != -1)
        {
            listBox1.SetSelected(index,true);
        }
        else 
            MessageBox.Show("Item not found!");
    }

Thanks in advance.

regards :)

Use StartsWith method to check if specific item starts with string you have entered:

private void searchBox_TextChanged(object sender, EventArgs e)
{
    string prefix = searchBox.Text;
    bool found = false;
    for(int i = 0; i < listBox.Items.Count; i++)
    {
        if(listBox.Items[i].ToString().StartsWith(prefix))
        {
            listBox.SelectedItem = listBox.Items[i];
            found = true;
            break;
        }
    }
    if(!found)
    {
        MessageBox.Show("Item not found!");
    }
}

From the details of FindString,

Finds the first item in the System.Windows.Forms.ListBox that starts with the specified string.

So you will have to custom write code to achieve it. Something like below,

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        string myString = textBox1.Text;
        bool found = false;
        for (int i = 0; i <= listBox1.Items.Count - 1; i++)
        {
            if(listBox1.Items[i].ToString().Contains(myString))
            {
                listBox1.SetSelected(i, true);
                found = true;
                break;
            }
        }                        
        if(!found)
        {
            MessageBox.Show("Item not found!");
        }                
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM