让你的输入文本框也具有记忆功能

来源:互联网 发布:手机怎么开通淘宝店 编辑:程序博客网 时间:2024/04/29 22:56

我们在用IE或者是Access时,一定都注意到这个很有意思的东西:输入文本框控件能通过匹配我们过去键入的内容来帮助我们自动添加完成我们要输入的内容,很是方便。但是,在我们编程时,这样花哨的功能并没有被封装在控件里。

其实,要教会它们这样做一点也不困难,涕淌以ComboBox控件为例(因为ComboBox用来做这个示例再合适不过了呵呵),给大家秀一段很简单的代码。其他的文本输入控件也是一样样的道理,我就不赘述了。

    Private Sub ComboBox1_KeyUp(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyUp
        AutoCompleteKeyUp(ComboBox1, e)
    End Sub

    Public Sub AutoCompleteKeyUp(ByVal Combo As ComboBox, ByVal e As KeyEventArgs)
        Dim strTyped As String
        Dim intFoundIndex As Integer
        Dim objFoundItem As Object
        Dim strFoundText As String
        Dim strAppendText As String
        '忽略这些基本操作键
        Select Case e.KeyCode
            Case Keys.Back, Keys.Left, Keys.Right, Keys.Up, _
                Keys.Delete, Keys.Down, Keys.CapsLock
                Return
        End Select
        '看看用户输入了些什么
        strTyped = Combo.Text
        intFoundIndex = Combo.FindString(strTyped)
        '如果找到了的话……
        If intFoundIndex >= 0 Then
            '获取Combo下的匹配项
            objFoundItem = Combo.Items(intFoundIndex)
            '获取匹配的字符串
            strFoundText = Combo.GetItemText(objFoundItem)
            '开始自动添加文本
            strAppendText = strFoundText.Substring(strTyped.Length)
            Combo.Text = strTyped & strAppendText
            '选亮添加的文本
            Combo.SelectionStart = strTyped.Length
            Combo.SelectionLength = strAppendText.Length
        End If
    End Sub

好了,你可以试试上面的代码。先在ComboBox的下拉列表里预存一些字符串吧,嘿嘿!

 
原创粉丝点击