我希望在与Listbox绑定的键值对列表上实现增量搜索。
如果有三个值(AAB,AAC,AAD),那么用户应该能够在可用列表框中选择一个项目并输入“AAC”,该项目应该被突出显示并聚焦。它还应该以增量方式进行。
处理此问题的最佳方法是什么?
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;
}
private string searchString;
private DateTime lastKeyPressTime;
TextChanged
事件,在用户输入字符时触发它,您还可以与此同时使用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;
}
getproducts
方法就会执行并填充列表框,并默认悬停在列表中的第一项。您还可以使用列表框事件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
,将所选文本添加到文本框中。