最近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 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,会导致异步线程出现异常)。

分类:

技术点:

相关文章: