How can I implement incremental search in a list?

I want to implement an incremental search on a list of key-value pairs associated with a Listbox.

If I had three values ​​(AAB, AAC, AAD), the user should be able to select an item in the available list and enter AAC, and this item should be highlighted and focused. It should also be phased.

What is the best approach for this?

+5
source share
4 answers

I understand that it is very late ... however, having just implemented it, I will leave it here, hoping that it will help someone.

Add a KeyChar event handler (in my case, the list is named lbxFieldNames):

private void lbxFieldNames_KeyPress(object sender, KeyPressEventArgs e)
{
  IncrementalSearch(e.KeyChar);
  e.Handled = true;
}

(: e.Handled = true;, listbox " , char" , , , .)

IncrementalSearch:

private void IncrementalSearch(char ch)
{
  if (DateTime.Now - lastKeyPressTime > new TimeSpan(0, 0, 1))
    searchString = ch.ToString();
  else
    searchString += ch;
  lastKeyPressTime = DateTime.Now;

  var item = lbxFieldNames
    .Items
    .Cast<string>()
    .Where(it => it.StartsWith(searchString, true, CultureInfo.InvariantCulture))
    .FirstOrDefault();
  if (item == null)
    return;

  var index = lbxFieldNames.Items.IndexOf(item);
  if (index < 0)
    return;

  lbxFieldNames.SelectedIndex = index;
}

, , , , TimeSpan if.

,

private string searchString;
private DateTime lastKeyPressTime;

, .

+6

, , , .

ComboBox ( ListBox):

+3

TextChanged , char, listbox DataSourceChanged, .

:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        listBox1.DataSource = GetProducts(textBox1.Text);
        listBox1.ValueMember = "Id";
        listBox1.DisplayMember = "Name";
    }

    List<Product> GetProducts(string keyword)
    {
        IQueryable q = from p in db.GetTable<Product>()
                       where p.Name.Contains(keyword)
                       select p;
        List<Product> products = q.ToList<Product>();
        return products;
    }

, - char, getproducts , , , listbox DataSourceChanged, - .

: TextBox.AutoCompleteCustomSource :

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

string[], , textbox, , :

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;
            }
        }

    }

ListBoxSelectedindexchanged,

+2

, TextChanged , , ( TextBox). , , , .

+1
source

All Articles