VB.NET中TextBox的智能感知運用實例。本站提示廣大學習愛好者:(VB.NET中TextBox的智能感知運用實例)文章只能為提供參考,不一定能成為您想要的結果。以下是VB.NET中TextBox的智能感知運用實例正文
本文實例情勢引見了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 Sub
End Class
這裡有一些留意點:
1)異步的異常不會拋出(由於異步的實質是CLR外部的線程),只能調試時刻看到。是以編寫異步法式必需萬分當心。
2)VB.NET界說數組(比方界說String(5)的數組,其實長度是6(從0~5)包括“5”本身,是以數組復制(Redim重界說年夜小)的時刻必需Count-1,不然從新界說的數組會多出一個來,默許是Nothing,這會招致異步線程湧現異常)。