本文實例形式介紹了VB.NET中TextBox的智能感知實現方法,功能非常實用,具體如下:
該實例主要實現:在TextBox中鍵入字符,可以智能感知出列表,同時對不存在的單詞(沒有出現智能感知的)自動顯示“Not Found”。
對此功能首先想到的是利用TextBox的AutoComplete功能。該功能允許你設置不同形式的AutoComplete智能感知,譬如:
1)AutoCompleteSource:設置感知源頭類型(這里是CustomSource)。
2)AutoCompleteMode:設置感知的模式(輸入不存在的字符追加,不追加還是同時存在,這里顯然不追加)。
3)AutoCompleteCustomSource:設置源頭數據(AutoCompleteSource必須是CustomSource)。
接下來思考如何在輸入第一個字符的時候判斷是否被感知到,如果沒有則顯示文本。
拖拽一個Label到窗體上,然后在TextBox的KeyUp事件中對數據源進行判斷(為了方便,直接先把數據源數據轉化成Array的形式然后使用擴展方法Any進行判斷),同時為了防止界面卡死,使用異步。
具體實現代碼如下:
Public Class Form1 Dim collection As New AutoCompleteStringCollection Private ReadOnly arrayCollection() As String = {"a"} Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load End Sub Public Sub New() InitializeComponent() collection.AddRange(New String() {"apple", "aero", "banana"}) TextBox1.AutoCompleteCustomSource = collection ReDim arrayCollection(collection.Count - 1) collection.CopyTo(arrayCollection, 0) End Sub ''' <summary> ''' When release the keys, plz start a background thread to handle the problem ''' </summary> Private Sub TextBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp Dim act As New Action(Sub() 'Check whether there are any values inside the collection or not If (TextBox1.Text = "") OrElse (arrayCollection.Any(Function(s) Return s.StartsWith(TextBox1.Text) End Function)) Then Label1.BeginInvoke(New MethodInvoker(Sub() Label1.Text = String.Empty End Sub)) Else Label1.BeginInvoke(New MethodInvoker(Sub() Label1.Text = "Not found" End Sub)) End If End Sub) act.BeginInvoke(Nothing, Nothing) End SubEnd Class
這里有一些注意點:
1)異步的異常不會拋出(因為異步的本質是CLR內部的線程),只能調試時候看到。因此編寫異步程序必須萬分小心。
2)VB.NET定義數組(譬如定義String(5)的數組,其實長度是6(從0~5)包含“5”自身,因此數組復制(Redim重定義大小)的時候必須Count-1,否則重新定義的數組會多出一個來,默認是Nothing,這會導致異步線程出現異常)。
新聞熱點
疑難解答