2016-02-13 37 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事件不會觸發。 –

相關問題