How can I implement incremental search on a listbox?

前端 未结 4 686
-上瘾入骨i
-上瘾入骨i 2021-01-19 00:19

I want to implement incremental search on a list of key-value pairs, bound to a Listbox.

If I had three values (AAB, AAC, AAD), then a user should be able to select

4条回答
  •  失恋的感觉
    2021-01-19 01:04

    You can use the TextChanged event to fire whenever the user enter a char, and you can also use the listbox event DataSourceChanged with it to hover a specific item or whatever you want.

    I will give you an example:

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            listBox1.DataSource = GetProducts(textBox1.Text);
            listBox1.ValueMember = "Id";
            listBox1.DisplayMember = "Name";
        }
    
        List GetProducts(string keyword)
        {
            IQueryable q = from p in db.GetTable()
                           where p.Name.Contains(keyword)
                           select p;
            List products = q.ToList();
            return products;
        }
    

    So whenever the user start to enter any char the getproducts method executes and fills the list box and by default hover the first item in the list you can handle that also using the listbox event DataSourceChanged to do whatever you want to do.

    There is also another interesting way to do that, which is: TextBox.AutoCompleteCustomSource Property:

    textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
    AutoCompleteStringCollection stringCollection = 
        new AutoCompleteStringCollection();
    textBox1.AutoCompleteCustomSource = stringCollection;
    

    This list can take only string[], so you can get them from your data source then when the text changed of the textbox add the similar words from your data source which had been filled into the textbox autocomplete custom source:

    private void textBox1_TextChanged(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            if (textBox1.Text.Length == 0)
            {
                listbox1.Visible = false;
                return;
            }
    
            foreach (String keyword in textBox1.AutoCompleteCustomSource)
            {
                if (keyword.Contains(textBox1.Text))
                {
                    listBox1.Items.Add(keyword);
                    listBox1.Visible = true;
                }
            }
    
        }
    

    Add another event ListBoxSelectedindexchanged to add the selected text to the text box

提交回复
热议问题