65.9K
CodeProject 正在变化。 阅读更多。
Home

自动完成文本框

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.70/5 (15投票s)

2011年8月20日

CPOL

1分钟阅读

viewsIcon

158199

downloadIcon

6356

本文档帮助创建带有自动完成功能的建议列表,并讨论了添加/删除操作。

引言

在项目工作期间,我需要使用一个控件,当用户键入时具有自动完成功能。我意识到我们可以使用文本框控件或组合框控件来实现这个目的。这两个控件都可以用来过滤记录,并以下拉列表的形式显示最佳匹配项。我将使用 VB.NET 来演示它。如果有人需要 C# 版本,可以使用在线转换器。我将讨论从下拉列表中添加和删除项目。

必备组件

在阅读本文档之前,我们需要了解 .NET Framework 2.0 中 Microsoft 引入的两个属性和一个枚举:AutoCompleteCustomSource 属性、AutoCompleteMode 属性和 AutoCompleteSource 枚举。

我们还应该了解 AutoCompleteStringCollection 类。

设计

自动完成源绑定到文本框的 AutoCompleteCustomSource 属性。它将帮助过滤建议列表中最合适的记录。

'Item is filled either manually or from database
Dim lst As New List(Of String)

'AutoComplete collection that will help to filter keep the records.
Dim MySource As New AutoCompleteStringCollection()

实现

我在 Form1_Load 事件中从名为 ‘lst’ 的列表中填充了源。这个列表也可以通过数据库填充。

Private Sub Form1_Load(ByVal sender As System.Object, _
	ByVal e As System.EventArgs) Handles MyBase.Load

    'Manually added some items
    lst.Add("apple")
    lst.Add("applle")
    lst.Add("appple")
    lst.Add("appplee")
    lst.Add("bear")
    lst.Add("pear")

    'Records binded to the AutocompleteStringCollection.
    MySource.AddRange(lst.ToArray)

    'this AutocompleteStringcollection binded to the textbox as custom
    'source.
    TextBox1.AutoCompleteCustomSource = MySource

    'Auto complete mode set to suggest append so that it will sugesst one
    'or more suggested completion strings it has bith ‘Suggest’ and
    '‘Append’ functionality
    TextBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend

    'Set to Custom source we have filled already
    TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource
End Sub

AutoCompleteSource 的操作

正如我之前讨论过的,我们将看到如何从绑定到 Textbox 源中添加/删除条目。

该事件使用此任务来实现的是 KeyDown 事件。

这里是带有解释的源代码

Private Sub TextBox1_KeyDown(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown

If e.KeyCode = Keys.Enter Then   ' On enter I planned to add it the list
     If Not lst.Contains(TextBox1.Text) Then  ' If item not present already
        ' Add to the source directly
         TextBox1.AutoCompleteCustomSource.Add(TextBox1.Text)
     End If
ElseIf e.KeyCode = Keys.Delete Then 'On delete key, planned to remove entry

' declare a dummy source
Dim coll As AutoCompleteStringCollection = TextBox1.AutoCompleteCustomSource

' remove item from new source
coll.Remove(TextBox1.Text)

' Bind the updates
TextBox1.AutoCompleteCustomSource = coll

' Clear textbox
TextBox1.Clear()

End If                   ' End of ‘KeyCode’ condition

End Sub

结论

还有更多关于整个工作原理的细节。我认为这是一个可行的自动完成 TextBox 解决方案,希望您觉得有趣。

© . All rights reserved.