2016-02-13 49 views
0

我有一个自动完成模式的文本框。当我输入前几个字符时,建议列表项目超过15个。 我希望建议项目最多显示10个项目。如何限制自动填充文本框中的下拉项目c#?

我没有找到属性来做到这一点。

AutoCompleteStringCollection ac = new AutoCompleteStringCollection(); 
ac.AddRange(this.Source()); 

if (textBox1 != null) 
{ 
    textBox1.AutoCompleteMode = AutoCompleteMode.Suggest; 
    textBox1.AutoCompleteCustomSource = ac; 
    textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; 
} 
+0

返回顶部10然后从数据 –

+1

''textBox1.AutoCompleteCustomSource = ac.Take(10)'' –

+0

@EhsanSajjad ac.Take()方法是不可用的。 –

回答

0

不能在AutoCompleteStringCollection类上使用LINQ。我建议你在TextBox的TextChanged事件中自己处理过滤。我在下面写了一些测试代码。输入一些文本后,我们将过滤并从Source()数据集中取前10个匹配项。然后我们可以为您的TextBox设置一个新的AutoCompleteCustomSource。我测试和工作的:

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

它的工作原理。但我不能使用“KEY DOWN”键向下滚动选择一个值。当我按下“KEY DOWN”时,首先在文本框中输入数值,然后下拉关闭 –

+0

然后使用KeyDown代替TextChanged事件,并且只在密钥不是Up/Down时刷新列表。 – Mangist

+0

KeyDown事件也不起作用。在建议下拉菜单中使用向上键或向下键时,Keydown事件不会触发。 –