During work on a project, I needed to use a control having auto complete facility in it as user types. I realized that we can make use of the textbox control or combobox control for this purpose. Both controls can be used to filter records as a drop down list to show the best matches. I will demonstrate it using VB.NET. If someone needs a C# version, an online converter can be used. I will be discussing the addition and removal of item from the drop down list.
Before reading this article, we need to be aware of two properties and an enumeration introduced by Microsoft in the .NET Framework 2.0 which is
AutoCompleteMode property and
We should also have a look at
An auto complete source is binded to the textbox’s
AutoCompleteCustomSource property. It will help to filter the best fit records in the suggestion list.
Dim lst As New List(Of String)
Dim MySource As New AutoCompleteStringCollection()
I have filled the source from the list named ‘
Form1_Load event. This list can be populated by the database as well.
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.AutoCompleteCustomSource = MySource
TextBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend
TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource
Operations on AutoCompleteSource
As I have discussed earlier that we will see how to add/ remove entry from the source, we have binded to the
The event uses this task to achieve is
Here is the source with explanation:
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 If Not lst.Contains(TextBox1.Text) Then TextBox1.AutoCompleteCustomSource.Add(TextBox1.Text)
ElseIf e.KeyCode = Keys.Delete Then
Dim coll As AutoCompleteStringCollection = TextBox1.AutoCompleteCustomSource
TextBox1.AutoCompleteCustomSource = coll
There are more details as to how the whole thing works. I feel this is a viable solution for an Auto-Complete
TextBox and I hope you find it interesting.