2014-10-30 54 views
3

我一直在使用代碼AutoCompleteStringCollection如何在C#中使用AutoComplete獲取事件「item selected」?

private void txtS_TextChanged(object sender, EventArgs e) 
    { 
     TextBox t = sender as TextBox; 
     string[] arr = this.dbService.GetAll(); 

     if (t != null) 
     { 
      if (t.Text.Length >= 3) 
      { 
       AutoCompleteStringCollection collection = new AutoCompleteStringCollection(); 
       collection.AddRange(arr);      
       this.txtSerial.AutoCompleteCustomSource = collection; 
      } 
     } 
    } 

我怎樣才能爲「選擇項」用戶選擇自動完成建議後的事件?和領域的價值?

+0

從自動完成列表中選擇的項目? – 2014-10-30 00:27:19

+0

是的。從「自動完成」列表中選擇的項目。 – 2014-10-30 00:31:21

回答

5

沒有這樣的事情,我相信你用於自動完成的文本框的選擇項目事件。你可以做的是添加一個按鍵事件到你的文本框。您可以驗證是否按下了回車鍵(單擊建議的鏈接與按回車鍵相同)。類似的東西:

private void textBox1_KeyDown(object sender, KeyEventArgs e) { 
    if (e.KeyData == Keys.Enter) { 
     String selItem = this.textBox1.Text; 
    } 
} 
+0

太棒了!謝謝! – 2014-11-05 03:41:35

1

簡短的回答:做一個自定義事件

龍答: 您可以攔截你的文本框的KeyDown事件的數字鍵盤輸入或正常的輸入和工具箱的鼠標雙擊事件比較工具箱的內容,然後觸發一個事件,如果他們匹配,代表會拿起。

0

與其專注於檢測是否選擇自動完成列表中的項目,而應該檢查文本框的當前值是否在自動填充項目集合中。

if (txtSerial.AutoCompleteCustomSource.Contains(t.Text)) 
{ 
    // Logic to handle an exact match being selected 
    ... 
} 
else 
{ 
    // Update the autocomplete entries based on what was typed in 
} 

如果這恰好是是自動完成的值列表內的確切字符串類型的用戶 - 或 - 他們選擇從自動完成列表中值 - 這應該產生任何不同的行爲?我認爲在大多數情況下它不應該。