2017-02-27 85 views
0

我見過幾個類似的老問題,但沒有一個得到正確回答,所以我再次提出這個話題。我需要的很簡單:我有一個由一個或幾個單詞組成的字符串列表(在這種情況下,用「,」分隔)。我想要一個文本框在用戶輸入時提示一個或多個字符串,但不僅要考慮字符串的第一個單詞,還要考慮其他單詞。作爲一個愚蠢的例子,如果我的字符串列表是:vb.net自動完成與分隔符

  • 串1:自行車,瑞迪施
  • 串2:汽車,紅色
  • 線3:貓,褐色

當用戶類型:建議使用「b」字符串1和3(自行車和棕色),當用戶輸入「c」或「ca」字符串2和3時應提示(汽車和貓)。

到目前爲止,我得到了自動完成屬性的工作,但只有第一個單詞(所以如果我的用戶鍵入「b」只會建議字符串1)。這是代碼:

Dim newstr As New AutoCompleteStringCollection 
While dr.Read 'this is a datareader from which I get my list 
    newstr.Add(dr.Item(0).ToString) 
End While 
dr.Close() 
mytextbox.AutoCompleteMode = AutoCompleteMode.SuggestAppend 
mytextbox.AutoCompleteSource = AutoCompleteSource.CustomSource 
mytextbox.AutoCompleteCustomSource = newstr 

我該如何實現我所需要的?我認爲它已經實施,但似乎沒有。任何幫助將不勝感激

+0

你必須找到一個現有的,包括到您的項目,或建立自己的。默認自動完成行爲僅從開始檢查 –

+0

我試圖找到一個,但到目前爲止沒有運氣 –

回答

1

我不認爲自動完成的來源是你想要這個。

相反,我建議你在DropDown模式下使用組合框。

ComboBox3.DropDownStyle = ComboBoxStyle.DropDown 

你需要做出的排行榜部分可見,當控件獲得聚焦...

Private Sub ComboBox3_GotFocus(sender As Object, e As EventArgs) Handles ComboBox3.GotFocus 
    ComboBox3.DroppedDown = True 
End Sub 

然後根據每當文本框的變化重建列表內容。

Private Sub ComboBox3_KeyUp(sender As Object, e As EventArgs) Handles ComboBox3.KeyUp 
    Dim Ss = ComboBox3.SelectionStart 
    Dim Sl = ComboBox3.SelectionLength 

.... rebuilt the list items here ... 

    Dim Ss = ComboBox3.SelectionStart 
    Dim Sl = ComboBox3.SelectionLength 
    ComboBox3.DroppedDown = True 
End Sub 

完整的例子

Public Class Form4 
Dim employees() As String = New String() {"Hamilton, David", _ 
     "Hensien, Kari", "Hammond, Maria", "Harris, Keith", _ 
     "Henshaw, Jeff D.", "Hanson, Mark", "Harnpadoungsataya, Sariya", _ 
     "Harrington, Mark", "Harris, Keith", "Hartwig, Doris", _ 
     "Harui, Roger", "Hassall, Mark", "Hasselberg, Jonas", _ 
     "Harnpadoungsataya, Sariya", "Henshaw, Jeff D.", "Henshaw, Jeff D.", _ 
     "Hensien, Kari", "Harris, Keith", "Henshaw, Jeff D.", _ 
     "Hensien, Kari", "Hasselberg, Jonas", "Harrington, Mark", _ 
     "Hedlund, Magnus", "Hay, Jeff", "Heidepriem, Brandon D."} 

Private Sub ComboBox3_GotFocus(sender As Object, e As EventArgs) Handles ComboBox3.GotFocus 
    ComboBox3.DroppedDown = True 
End Sub 

Private Sub ComboBox3_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboBox3.KeyUp 

    Dim Ss = ComboBox3.SelectionStart ' + 1 

    ComboBox3.Items.Clear() 

    Dim SearchText As String = UCase(ComboBox3.Text) 
    For Each Str As String In employees 
     Dim UStr As String = UCase(Str) 
     If InStr(UStr, SearchText) = 1 OrElse InStr(UStr, " " & SearchText) > 0 Then 
      ComboBox3.Items.Add(Str) 
     End If 

    Next 
    ComboBox3.SelectionStart = Ss 
    ComboBox3.SelectionLength = 0 
    ComboBox3.DroppedDown = True 
End Sub 
End Class 

確保您設置comboboxstyle到下拉

enter image description here

+0

您能否給我看一個簡單的例子?我試圖按照你的方案,但它不工作。只要我篩選列表項,第一個被選中(覆蓋用戶輸入的內容)。謝謝! –

+0

查看更新@CarlosBorau –

+0

真棒,謝謝!似乎關鍵在於Items.Clear()方法 –