如何在列表框上实现增量搜索? [英] How can I implement incremental search on a listbox?

查看:132
本文介绍了如何在列表框上实现增量搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果我有三个值(AAB,AAC,AAD),那么我将在一个键值对的列表上实现增量搜索。 ,则用户应该能够在可用列表框中选择项目并输入AAC,并且该项目应该被突出显示并且聚焦。



$ b

这是最好的处理方法是什么?

解决方案

我意识到这是非常晚的...但是,刚刚实现了,我会把它留在这里,希望它会帮助一个人。



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

  private void lbxFieldNames_KeyPress发送者,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 语句中。



将需要声明

  private string searchString; 
private DateTime lastKeyPressTime;

希望这有帮助。


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 an item in the available list box and type AAC and this item should be highlighted and in focus. It should be also in incremental fashion.

What is the best approach to handle this?

解决方案

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

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.

这篇关于如何在列表框上实现增量搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆