How can I implement incremental search on a listbox?

前端 未结 4 682
-上瘾入骨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 00:57

    I realize this is extremely late... however, having just implemented this, I'll leave it here in the hope that it will help someone.

    Add a handler to the KeyChar event (the listbox is named lbxFieldNames in my case):

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

    (Important: you need e.Handled = true; because the listbox implements a "go to the first item starting with this char" search by default; it took me a while to figure out why my code was not working.)

    The IncrementalSearch method is:

    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()
        .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;
    }
    

    The timeout I implemented is one second, but you can change it by modifying the TimeSpan in the if statement.

    Finally, you will need to declare

    private string searchString;
    private DateTime lastKeyPressTime;
    

    Hope this helps.

提交回复
热议问题