如何在列表框上实现增量搜索?

Dha*_*ana 5 c# listbox winforms

我想在绑定到列表框的键值对列表上实现增量搜索.

如果我有三个值(AAB,AAC,AAD),则用户应该能够在可用列表框中选择一个项目并键入AAC,此项应突出显示并处于焦点.它也应该是渐进的方式.

处理这个问题的最佳方法是什么?

Mar*_*scu 6

我意识到这已经很晚了......但是,刚刚实施了这个,我会把它留在这里,希望它会帮助别人.

为KeyChar事件添加一个处理程序(在我的例子中,列表框被命名为lbxFieldNames):

private void lbxFieldNames_KeyPress(object sender, KeyPressEventArgs e)
{
  IncrementalSearch(e.KeyChar);
  e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)

(重要:您需要,e.Handled = true;因为列表框默认实现"转到以此字符开头的第一个项目"搜索;我花了一些时间来弄清楚我的代码无法正常工作的原因.)

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;
}
Run Code Online (Sandbox Code Playgroud)

我执行超时为一秒,但是你可以通过修改改变它TimeSpanif声明.

最后,您需要申报

private string searchString;
private DateTime lastKeyPressTime;
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


Gra*_*ICA 4

如果我正确解释您的问题,您似乎希望用户能够开始输入并提出建议。

您可以使用组合框(而不是列表框):

  1. DataSource设置为您的 KeyValuePairs 列表,
  2. 将 ValueMember 设置为“Key”,将 DisplayMember 设置为“Value”,
  3. AutoCompleteMode设置为 SuggestAppend,并且
  4. 将AutoCompleteSource设置为 ListItems