如何限制自动完成文本框 C# 中的下拉项
本文关键字:文本 何限制 | 更新日期: 2023-09-27 18:34:37
我有一个带有自动完成模式的文本框。当我输入前几个字符时,建议列表项超过 15 个。我希望建议项最多显示 10 个项。
我找不到财产来做这件事。
AutoCompleteStringCollection ac = new AutoCompleteStringCollection();
ac.AddRange(this.Source());
if (textBox1 != null)
{
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteCustomSource = ac;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
不能在 AutoCompleteStringCollection 类上使用 LINQ。我建议您在文本框的TextChanged事件中自己处理过滤。我在下面写了一些测试代码。输入一些文本后,我们将从您的 Source(( 数据集中过滤并获取前 10 个匹配项。然后,我们可以为您的文本框设置一个新的自动完成自定义源。我测试了它,这有效:
private List<string> Source()
{
var testItems = new List<string>();
for (int i = 1; i < 1000; i ++)
{
testItems.Add(i.ToString());
}
return testItems;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
var topTenMatches = this.Source().Where(s => s.Contains(textBox1.Text)).Take(10);
var autoCompleteSource = new AutoCompleteStringCollection();
autoCompleteSource.AddRange(topTenMatches.ToArray());
textBox1.AutoCompleteCustomSource = autoCompleteSource;
}