手机
当前位置:查字典教程网 >编程开发 >C#教程 >VB.NET中TextBox的智能感知应用实例
VB.NET中TextBox的智能感知应用实例
摘要:本文实例形式介绍了VB.NET中TextBox的智能感知实现方法,功能非常实用,具体如下:该实例主要实现:在TextBox中键入字符,可以智...

本文实例形式介绍了VB.NET中TextBox的智能感知实现方法,功能非常实用,具体如下:

该实例主要实现:在TextBox中键入字符,可以智能感知出列表,同时对不存在的单词(没有出现智能感知的)自动显示“Not Found”。

对此功能首先想到的是利用TextBox的AutoComplete功能。该功能允许你设置不同形式的AutoComplete智能感知,譬如:

1)AutoCompleteSource:设置感知源头类型(这里是CustomSource)。

2)AutoCompleteMode:设置感知的模式(输入不存在的字符追加,不追加还是同时存在,这里显然不追加)。

3)AutoCompleteCustomSource:设置源头数据(AutoCompleteSource必须是CustomSource)。

接下来思考如何在输入第一个字符的时候判断是否被感知到,如果没有则显示文本。

拖拽一个Label到窗体上,然后在TextBox的KeyUp事件中对数据源进行判断(为了方便,直接先把数据源数据转化成Array的形式然后使用扩展方法Any进行判断),同时为了防止界面卡死,使用异步。

具体实现代码如下:

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

【VB.NET中TextBox的智能感知应用实例】相关文章:

C#中通过API实现的打印类 实例代码

在C#中 webbrowser的使用心得

c#剪切板操作的简单实例

.NET中的静态与非静态的区别分析

c# 应用事务的简单实例

深入IComparable与IComparer的排序实例详解

C# LINQ to XML应用介绍

C#中无边框窗体移动的简单实例

C# 获取枚举值的简单实例

C#反射在实际应用中的实例代码

精品推荐
分类导航