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

标签 c# winforms listbox

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

如果我有三个值(AAB、AAC、AAD),那么用户应该能够在可用列表框中选择一个项目并键入 AAC,并且该项目应该突出显示并处于焦点状态。它也应该以增量方式进行。

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

最佳答案

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

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

(重要:您需要 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;
}

我实现的超时是一秒,但是你可以通过修改if语句中的TimeSpan来改变它。

最后,你需要声明

private string searchString;
private DateTime lastKeyPressTime;

关于c# - 如何在列表框上实现增量搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7556318/

相关文章:

c# - 在 Control.GotFocus 中检测用户是否向前或向后导航?

c# - WinForms:为什么在显示文件夹浏览器对话框时出现 InvalidCastException?

python - 相同高度的 Tkinter 列表框和复选框

c# - 如何从 C# 或 C/C++ 嵌入和运行 .exe

c# - 具有通用 ID 的通用存储库 - 如何在 int 时检索

c# - 将字节插入文件中间(在 Windows 文件系统中)而不读取整个文件(使用文件分配表)?

c# - 如何找出最上面的表格?

wpf - 在其他控件旁边显示 itemtemplate 中的用户控件列表

windows-phone-7 - ListBox的ControlTemplate样式时如何保持虚拟化?

c# - HttpContext.Current.Response.AddHeader() 未设置 Content-Type header