VB.NET中TextBox的智能感知應(yīng)用實例
本文實例形式介紹了VB.NET中TextBox的智能感知實現(xiàn)方法,功能非常實用,具體如下:
該實例主要實現(xiàn):在TextBox中鍵入字符,可以智能感知出列表,同時對不存在的單詞(沒有出現(xiàn)智能感知的)自動顯示“Not Found”。
對此功能首先想到的是利用TextBox的AutoComplete功能。該功能允許你設(shè)置不同形式的AutoComplete智能感知,譬如:
1)AutoCompleteSource:設(shè)置感知源頭類型(這里是CustomSource)。
2)AutoCompleteMode:設(shè)置感知的模式(輸入不存在的字符追加,不追加還是同時存在,這里顯然不追加)。
3)AutoCompleteCustomSource:設(shè)置源頭數(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重定義大?。┑臅r候必須Count-1,否則重新定義的數(shù)組會多出一個來,默認是Nothing,這會導致異步線程出現(xiàn)異常)。
相關(guān)文章
WinForm判斷關(guān)閉事件來源于用戶點擊右上角“關(guān)閉”按鈕的方法
這篇文章主要介紹了WinForm判斷關(guān)閉事件來源于用戶點擊右上角“關(guān)閉”按鈕的方法,涉及C#針對WinForm事件的判定技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09C#中泛型容器Stack<T>的用法并實現(xiàn)”撤銷/重做”功能
這篇文章介紹了C#中泛型容器Stack<T>的用法并實現(xiàn)”撤銷/重做”功能,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-10-10Unity編輯器資源導入處理函數(shù)OnPostprocessAudio使用案例
這篇文章主要為大家介紹了Unity編輯器資源導入處理函數(shù)OnPostprocessAudio使用案例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08