TextBox的智能感知
最近MSDN回答一個問題——說如果在TextBox中鍵入字符,需要智能感知出列表,同時對不存在的單詞(沒有出現智能感知的)自動顯示“Not Found”。
首先想到的是利用TextBox的AutoComplete功能。該功能允許你設置不同形式的AutoComplete智能感知,譬如:
? ? ? ?1)AutoCompleteSource:設置感知源頭類型(這里是CustomSource)。
2)AutoCompleteMode:設置感知的模式(輸入不存在的字符追加,不追加還是同時存在,這里顯然不追加)。
? ? ? ?3)AutoCompleteCustomSource:設置源頭數據(AutoCompleteSource必須是CustomSource)。
接下來思考如何在輸入第一個字符的時候判斷是否被感知到,如果沒有則顯示文本。
拖拽一個Label到窗體上,然后在TextBox的KeyUp事件中對數據源進行判斷(為了方便,直接先把數據源數據轉化成Array的形式然后使用擴展方法Any進行判斷),同時為了防止界面卡死,使用異步,代碼如下(VB.NET):
Public Class Form1Dim collection As New AutoCompleteStringCollectionPrivate ReadOnly arrayCollection() As String = {"a"}Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.LoadEnd SubPublic Sub New()InitializeComponent()collection.AddRange(New String() {"apple", "aero", "banana"})TextBox1.AutoCompleteCustomSource = collectionReDim 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.KeyUpDim act As New Action(Sub()'Check whether there are any values inside the collection or notIf (TextBox1.Text = "") OrElse (arrayCollection.Any(Function(s)Return s.StartsWith(TextBox1.Text)End Function)) ThenLabel1.BeginInvoke(New MethodInvoker(Sub()Label1.Text = String.EmptyEnd Sub))ElseLabel1.BeginInvoke(New MethodInvoker(Sub()Label1.Text = "Not found"End Sub))End IfEnd Sub)act.BeginInvoke(Nothing, Nothing)End Sub End Class這里有一些注意點:
1)異步的異常不會拋出(因為異步的本質是CLR內部的線程),只能調試時候看到。因此編寫異步程序必須萬分小心。
2)VB.NET定義數組(譬如定義String(5)的數組,其實長度是6(從0~5)包含“5”自身,因此數組復制(Redim重定義大小)的時候必須Count-1,否則重新定義的數組會多出一個來,默認是Nothing,會導致異步線程出現異常)。
轉載于:https://www.cnblogs.com/ServiceboyNew/archive/2013/04/30/3051772.html
總結
以上是生活随笔為你收集整理的TextBox的智能感知的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习之多分类学习
- 下一篇: javax.servlet.jsp.Pa