Click here to Skip to main content
15,917,481 members
Articles / Programming Languages / Visual Basic

AutoComplete Textbox

Rate me:
Please Sign up or sign in to vote.
4.70/5 (16 votes)
30 Dec 2011CPOL1 min read 156.1K   6.3K   22   13
This article helps to create a suggestion list with autocomplete facility, add/remove operation is also discussed.

Introduction

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.

Prerequisites

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 AutoCompleteCustomSource property, AutoCompleteMode property and AutoCompleteSource enumeration.

We should also have a look at AutoCompleteStringCollection class.

Design

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.

VB.NET
'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()

Implementation

I have filled the source from the list named ‘lst’ at Form1_Load event. This list can be populated by the database as well.

VB.NET
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

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 Textbox’s source.

The event uses this task to achieve is KeyDown event.

Here is the source with explanation:

VB.NET
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

Conclusion

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer eHealthWorks LLC
Pakistan Pakistan
I satisfy my daily 'urge to code' by participating in forums:

On Experts-Exchange:
Screen Name : Shahan_Developer

On MSDN:
Screen Name : EngrShahan

On C-Sharp Corner:
Screen Name : ShahanDev

On DaniWeb IT Community:
Screen Name : ShahanDev

Comments and Discussions

 
GeneralVery useful Pin
alecs.mkd12-Jun-15 2:29
alecs.mkd12-Jun-15 2:29 
AnswerRe: Error AutoComplete "AccessViolationException" Pin
om3n30-Jul-12 18:55
om3n30-Jul-12 18:55 
GeneralRe: Error AutoComplete "AccessViolationException" Pin
Shahan Ayyub30-Jul-12 18:58
Shahan Ayyub30-Jul-12 18:58 
QuestionError AutoComplete "AccessViolationException" Pin
om3n29-Jul-12 17:28
om3n29-Jul-12 17:28 
AnswerRe: Error AutoComplete "AccessViolationException" Pin
Shahan Ayyub30-Jul-12 7:55
Shahan Ayyub30-Jul-12 7:55 
QuestionRe: Error AutoComplete "AccessViolationException" Pin
om3n30-Jul-12 17:51
om3n30-Jul-12 17:51 
thank you for your suggestion, I've tried as you suggest :

1) First step, if I run one by one (start the application and then enter the word on TBArtist, I get the result, then I close the application. and vice versa). I also have tried :
I typed in the TBArtist, a result I managed to get the Artist's data after that I typed again in the TBOwner. when I enter the first character of the word "MR" there is no error message, when I enter the second character is "R" I get the error message :
"AccessViolationException was unhandled"
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
System.AccessViolationException was unhandled
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at Inventory.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:

2) Of course, I also tried to use first textbox with code written for second textbox, I put first texbox code to the second texbox the result get error message "AccessViolationException was unhandled". I close the application with curiosity and then I run the application again by entering a word into the first textbox, the result is the same error message.
then I clean up the solution & my project by going to menu Build -> CLEAN SOLUTION and BUILD -> CLEAN PROJECT. then I tried again and the result is the same error message, even when I return to the code structure as the original condition and I am trying to give it back but the result is the same error message "AccessViolationException was unhandled".

3) I've tried it, below is the code I use
STEP 1 => The result is the same error message
==============================================
VB
Private Sub TBMedium_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TBMedium.TextChanged
    TBOwner.AutoCompleteMode = AutoCompleteMode.None
    Call OpenAuction()
    CommandAuct.Connection = ConAuct
    CommandAuct.CommandType = CommandType.Text
    CommandAuct.CommandText = "SELECT mda_desc FROM tmedia"
    ObjDtAdapterAuct.SelectCommand = CommandAuct
    ObjDtAdapterAuct.Fill(objDataSetAuct, "Medium")

    Dim ColMedium As New AutoCompleteStringCollection
    Dim i As Integer
    For i = 0 To objDataSetAuct.Tables("Medium").Rows.Count - 1
        ColMedium.Add(objDataSetAuct.Tables("Medium").Rows(i)("mda_desc").ToString())
    Next
    TBMedium.AutoCompleteSource = AutoCompleteSource.CustomSource
    TBMedium.AutoCompleteCustomSource = ColMedium
    TBMedium.AutoCompleteMode = AutoCompleteMode.Suggest
    CommandAuct.Dispose()
    ObjDtAdapterAuct.Dispose()
    ConAuct.Close()
End Sub


STEP 2 => There is no any results
=================================
VB
Private Sub TBMedium_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TBMedium.TextChanged
        TBOwner.AutoCompleteMode = AutoCompleteMode.None
        TBMedium.AutoCompleteMode = AutoCompleteMode.None
        Call OpenAuction()
        CommandAuct.Connection = ConAuct
        CommandAuct.CommandType = CommandType.Text
        CommandAuct.CommandText = "SELECT mda_desc FROM tmedia"
        ObjDtAdapterAuct.SelectCommand = CommandAuct
        ObjDtAdapterAuct.Fill(objDataSetAuct, "Medium")

        Dim ColMedium As New AutoCompleteStringCollection
        Dim i As Integer
        For i = 0 To objDataSetAuct.Tables("Medium").Rows.Count - 1
            ColMedium.Add(objDataSetAuct.Tables("Medium").Rows(i)("mda_desc").ToString())
        Next
        TBMedium.AutoCompleteSource = AutoCompleteSource.CustomSource
        TBMedium.AutoCompleteCustomSource = ColMedium
        TBMedium.AutoCompleteMode = AutoCompleteMode.Suggest
        CommandAuct.Dispose()
        ObjDtAdapterAuct.Dispose()
        ConAuct.Close()
    End Sub


4) I finally thought maybe this is a bug of Visual Studio 2010 with. net framework 4.

from the way I have done, what do you think? D'Oh! | :doh:
QuestionMore like a Tip Pin
PIEBALDconsult30-Dec-11 4:36
mvePIEBALDconsult30-Dec-11 4:36 
AnswerRe: More like a Tip Pin
Shahan Ayyub2-Jan-12 23:05
Shahan Ayyub2-Jan-12 23:05 
GeneralMy vote of 5 Pin
Ahmed_online30-Dec-11 2:33
Ahmed_online30-Dec-11 2:33 
GeneralMy vote of 2 Pin
khaled.mufti27-Dec-11 19:19
khaled.mufti27-Dec-11 19:19 
GeneralMy vote of 5 Pin
Mavusana23-Dec-11 1:20
Mavusana23-Dec-11 1:20 
Generalthank you a lot Pin
Amila thennakoon10-Sep-11 6:33
Amila thennakoon10-Sep-11 6:33 
GeneralRe: thank you a lot Pin
Shahan Ayyub10-Sep-11 6:57
Shahan Ayyub10-Sep-11 6:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.