Click here to Skip to main content
Click here to Skip to main content

AutoComplete ComboBox in VB.Net

By , 7 May 2002
 

Introduction

This is an AutoCompleting ComboBox that works with Data Bound or Regular ComboBoxes in VB.NET. As you type the case is preserved but the remaining text is auto filled by the list items. When the Leave function is called the case is fixed and the index from the list is also selected if there is a matching item.

Sample Image - AutoComplete_ComboBox.gif

Call the corresponding functions from your Combobox's KeyUp and Leave events like so:

Private Sub cboName_Leave(ByVal sender As Object, ByVal e As System.EventArgs) 
                                                            Handles cboName.Leave
    Dim recRowView As DataRowView
    Dim recName As DB.tblNameRow

    AutoCompleteCombo_Leave(cboName)

    'OPTIONAL: Now you can  do some extra handling if you want

    'Get the Selected Record from my Data Bound Combo (Return Type is DataRowView)
    recRowView = cboName.SelectedItem
    If recRowView Is Nothing Then Exit Sub

    'Display the Name Info (Row Type comes from my bound Dataset)
    recName = recRowView.Row
    lblAccountNum.Text = recName.AccountNum
    lblCompanyName.Text = recName.CompanyName

End Sub

Private Sub cboName_KeyUp(ByVal sender As Object, 
              ByVal e As System.Windows.Forms.KeyEventArgs) Handles cboName.KeyUp

    AutoCompleteCombo_KeyUp(cboName, e)

End Sub

Here are the Generic Functions for handling the events:

Public Sub AutoCompleteCombo_KeyUp(ByVal cbo As ComboBox, ByVal e As KeyEventArgs)
    Dim sTypedText As String
    Dim iFoundIndex As Integer
    Dim oFoundItem As Object
    Dim sFoundText As String
    Dim sAppendText As String

    'Allow select keys without Autocompleting
    Select Case e.KeyCode
        Case Keys.Back, Keys.Left, Keys.Right, Keys.Up, Keys.Delete, Keys.Down
            Return
    End Select

    'Get the Typed Text and Find it in the list
    sTypedText = cbo.Text
    iFoundIndex = cbo.FindString(sTypedText)

    'If we found the Typed Text in the list then Autocomplete
    If iFoundIndex >= 0 Then

        'Get the Item from the list (Return Type depends if Datasource was bound 
        ' or List Created)
        oFoundItem = cbo.Items(iFoundIndex)

        'Use the ListControl.GetItemText to resolve the Name in case the Combo 
        ' was Data bound
        sFoundText = cbo.GetItemText(oFoundItem)

        'Append then found text to the typed text to preserve case
        sAppendText = sFoundText.Substring(sTypedText.Length)
        cbo.Text = sTypedText & sAppendText

        'Select the Appended Text
        cbo.SelectionStart = sTypedText.Length
        cbo.SelectionLength = sAppendText.Length

    End If

End Sub


Public Sub AutoCompleteCombo_Leave(ByVal cbo As ComboBox)
    Dim iFoundIndex As Integer

    iFoundIndex = cbo.FindStringExact(cbo.Text)

    cbo.SelectedIndex = iFoundIndex

End Sub

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Daryl
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: ComboBox Control in VB.NetgroupAnkitaaguggi7 Oct '11 - 0:16 
Hello,
very nice article !!!! really great stuff, thanks for sharing with us. it's help me a lot and this link
http://www.mindstick.com/Articles/6954dd86-57df-41c0-9ced-43d40d4fb255/?ComboBox%20Control%20in%20VB.Net[^]
is also helped me lot in completing my project.
 
Thumbs Up | :thumbsup: Thanks !!!!!!
GeneralMy vote of 5memberprodigytechnologies28 Apr '11 - 1:16 
Great solution.
Thnks
GeneralThank youmemberZestelle16 Sep '09 - 5:02 
I'm new to VB.Net and I found it surprising that this kind of behavior was not built in the basic combobox control?!
 
So thank you very much for the code, I found it really helpful.
 
It works exactly as I wanted. Thumbs Up | :thumbsup: Big Grin | :-D
 
Zestelle
AnswerProblem in Access database querymemberAyesha.Hafeez16 Dec '08 - 5:35 
I am receiving problem like sysntax error in INSERT INTO statement. I checked it again n again but I am unable to find eror in this code segment if anyone can help i will appeciate their concern.
code segment is
cmd = New OleDbCommand("INSERT INTO Transaction VALUES('" & WithDrawTxt.Text & "','" & AccountNo.ToString & "','" & dt.ToString & "')", cn)
i = cmd.ExecuteNonQuery
Table INFO
Table Transaction has fields Amount, Account_Number, Transaction_Date and last is Transaction#. All have field text except Transaction# which is auto number.
GeneralRe: Problem in Access database querymemberbwarehouse23 Feb '09 - 16:01 
MS Access rejects some non-alphanumeric characters like ' (apostrophe), if not formatted properly. Try this: cmd = New OleDbCommand("INSERT INTO Transaction VALUES('" & WithDrawTxt.Text.Replace("'","''") & "', '" & AccountNo.ToString & "', '" & dt.ToString & "')", cn). Also, for inserting numbers into MS Access Database, you may find it easier if you set the "AccountNo" field in the database to "Number", instead of "Text". This way, you can remove the ' (apostrophes) surrounding your number in the sql string ('" & AccountNo.ToString & "','"). If you do change the MS Access field type to "Number", the sql string should look like this: cmd = New OleDbCommand("INSERT INTO Transaction VALUES('" & WithDrawTxt.Text.Replace("'","''") & "', " & AccountNo & ", '" & dt.ToString & "')", cn).
One last observation; I don't know what format "dt" is in, but if you have the MS Access field set to "DateTime", and you are attempting to send it a string value (dt.ToString)(if dt is a date in string format), then that will fail every time. If dt.ToString is in some type of "date/datetime" format, you have to enclose the value with the # (pound sign), like this: ...,'" & AccountNo.ToString & "', #" & dt.ToString & "#)", cn)
 
Hope this helps.
 
b.ware,
A.P.W.S (A programmer without sleep)
 
b.ware,
A.P.W.S (A programmer without sleep)
GeneralAutocomplete Questionmembermchlcmprch29 Oct '07 - 13:29 
I seem to be (as usual) confused by the behaviour of autocomplete combos. Is it my imagination or do autocomplete combos change their selected indexes when they are selected? I have an app where this seems to be happening... a little background...
 
On a winform I have three combos all populated from the same arraylist.A concept number, an item number and a name, all related and associated. there are occasions when, for instance, I have set the selectedindex to, say 122, via selecting a concept number, and when I click or tab to the next combo, the selected indexes seem to be set to 0! Very irritating. This is definately in some way due to autocomplete, because if I make them all autocomplete false this doesn't happen. Unfortunately there is a reqirement for autocomplete.... I'm really frustrated and all my googling has not yet gotten me an solution!
 
Michael S. Comperchio
michael.comperchio@hotmail.com
203 218 4053
GeneralAutocomplete suggestion must try..memberSamee Dars16 Mar '08 - 22:44 
please try following properties to enable autocomplete feature for combo box...
set theese properties form property window...
cb.AutoCompleteSource=ListItems //there are other options also...
cb.AutoCompleteMode=SuggestAppend //there are differnets modes available u can try them also....
 

 
for code try this....
this.cb.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.cb.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
 
[$@^^€€]

GeneralRe: Autocomplete suggestionmemberSamee Dars16 Mar '08 - 22:58 
sorry there that feature works in 2.0 Frown | :(
 
[$@^^€€]

GeneralRe: Autocomplete suggestionmemberdibblm-Ohio9 Jan '09 - 5:31 
Its works for me. thank you soooooo much.
 
Im a fairly novice programmer and I dont know how to state what Im looking for. I ran into the original post. Saw all the code he had to go through and decided to see if someone had modified it any when I ran into your post.
 
Works like a charm. Only the page flutters a couple time after you select a record. Any idea why ?
 
Mike Dibble

Generalthankmemberansing20 Jan '07 - 3:31 
i find the code very helpful for a beginner like me....thanks
 
more power
 
knowlege is a treasure but practice is the key

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 8 May 2002
Article Copyright 2002 by Daryl
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid