VB.NET中TextBox的智能感知應用實例
本文實例形式介紹了VB.NET中TextBox的智能感知實現(xiàn)方法,功能非常實用,具體如下:
該實例主要實現(xiàn):在TextBox中鍵入字符,可以智能感知出列表,同時對不存在的單詞(沒有出現(xiàn)智能感知的)自動顯示“Not Found”。
對此功能首先想到的是利用TextBox的AutoComplete功能。該功能允許你設置不同形式的AutoComplete智能感知,譬如:
1)AutoCompleteSource:設置感知源頭類型(這里是CustomSource)。
2)AutoCompleteMode:設置感知的模式(輸入不存在的字符追加,不追加還是同時存在,這里顯然不追加)。
3)AutoCompleteCustomSource:設置源頭數(shù)據(jù)(AutoCompleteSource必須是CustomSource)。
接下來思考如何在輸入第一個字符的時候判斷是否被感知到,如果沒有則顯示文本。
拖拽一個Label到窗體上,然后在TextBox的KeyUp事件中對數(shù)據(jù)源進行判斷(為了方便,直接先把數(shù)據(jù)源數(shù)據(jù)轉(zhuǎn)化成Array的形式然后使用擴展方法Any進行判斷),同時為了防止界面卡死,使用異步。
具體實現(xiàn)代碼如下:
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)異步的異常不會拋出(因為異步的本質(zhì)是CLR內(nèi)部的線程),只能調(diào)試時候看到。因此編寫異步程序必須萬分小心。
2)VB.NET定義數(shù)組(譬如定義String(5)的數(shù)組,其實長度是6(從0~5)包含“5”自身,因此數(shù)組復制(Redim重定義大小)的時候必須Count-1,否則重新定義的數(shù)組會多出一個來,默認是Nothing,這會導致異步線程出現(xiàn)異常)。
相關(guān)文章
C#客戶端程序Visual Studio遠程調(diào)試的方法詳解
這篇文章主要給大家介紹了關(guān)于C#客戶端程序Visual Studio遠程調(diào)試的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-09-09
C# winfrom 模擬ftp文件管理實現(xiàn)代碼
從網(wǎng)上找到的非常好用的模擬ftp管理代碼,整理了一下,希望對需要的人有幫助2014-01-01

