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: Save Combo BoxmemberdELm5 Feb '04 - 15:22 
1- databases (mysql, msqls, etc) -> if you are working with large amounts of complex data...
2- XML -> save/load to/from a xml file.
3- ini -> save/load to/from a ini file.
if you want more info about these files, search in this same site.
GeneralRe: Save Combo Boxsussaniepras30 Dec '04 - 7:24 
easiest way is to use a database

GeneralEscapesussAnonymous15 Oct '03 - 17:48 
I created a new combobox control based on the codes. But why it seems when the combobox item list is currently dropdown, as i key in the characters, when I press key, and leave the combobox, the text remain as it is but the actual index is actually at the previously selected item. The key also seems to have the same kind of observation. How to solve it?
GeneralDB.tblnameRowmembervb_me10 Sep '03 - 15:51 
I too am not sure what this is ???
GeneralJust One SubmemberLaurent Muller11 Aug '03 - 3:41 
Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
 
If Char.IsControl(e.KeyChar) Then Return
 
With Me.ComboBox1
 
Dim ToFind As String = .Text.Substring(0, .SelectionStart) & e.KeyChar
Dim Index As Integer = .FindStringExact(ToFind)
 
If Index = -1 Then Index = .FindString(ToFind)
If Index = -1 Then Return
 
.SelectedIndex = Index
.SelectionStart = ToFind.Length
.SelectionLength = .Text.Length - .SelectionStart
 
e.Handled = True
 
End With
End Sub

GeneralRe: Just One SubmemberBehram9 Sep '03 - 13:29 
Laurent - I have "Just One Word" for your "Just One Sub" ... Genius.
GeneralRe: Just One SubmemberLaurent Muller9 Sep '03 - 23:02 
Thank You Smile | :)
GeneralRe: Just One SubsussAnonymous22 Nov '03 - 6:32 
All the more so because the original example does strange things when you tab into the control. It isn't anything that is hard to handle, and the code still works, but if you are designing to the lowest common user denominator, you want things to behave like they typically do in other windows programs.
I found autocomplete code for vb.net on msdn once, but since I forgot to save the link/code D'Oh! | :doh: I'm sure glad I found you guys.
Thanks for the code!
GeneralRe: Just One Sub, slight change,memberkoo93 Dec '03 - 9:44 
add this
 
Me.ComboBox1.DropDown = True;
If Char.IsControl(e.KeyChar) Then Return
 
It will work like that address bar in IE.

GeneralRe: Just One Sub, slight change,sussMark Lam16 Feb '04 - 5:58 
koo9 wrote:
Me.ComboBox1.DropDown = True;
 
This didn't quite work for me - I had to do this:
 
If cbCarrierCompNum.DropDownStyle = ComboBoxStyle.DropDown Then
cbCarrierCompNum.DroppedDown = True
End If

 
There's probably a better way of doing it, but now it works like IE. The original way threw an error about needing to raise an event.
 
Otherwise, very simple, elegant and to the point.Smile | :)
 
Mark
GeneralRe: Just One Sub, slight change,memberPizza_spaghetti_giova_arezzoèé28 Apr '04 - 13:47 
Mad | :mad: an intresting situation..Blush | :O
 
AnItalianBigK..
GeneralRe: Just One Sub, slight change,sussAnonymous3 Mar '05 - 10:36 
Me.ComboBox1.DroppedDown = True;
If Char.IsControl(e.KeyChar) Then Return

GeneralRe: Just One Sub, slight change,memberclangl19 Jun '06 - 7:34 
I have been trying to tweak this a little...
When ever I deleted the entry from the Combo Box it would not persist to the DB...
Here is what I did BUT...... I can only use the Backspace.... Not the Delete Key... Not sure why yet...
 
If Char.IsControl(e.KeyChar) Then
'If PotAdm2CmbBox.Text.Length = 0 Then PotAdm2CmbBox.SelectedIndex = -1
If PotAdm2CmbBox.SelectedText.Length = PotAdm2CmbBox.Text.Length And e.KeyChar = Microsoft.VisualBasic.ChrW(8) Then
PotAdm2CmbBox.SelectedIndex = -1
End If
Return
End If
 
***************
When the delete key is pressed it does not fire the keypress event for some reason....
 
-Chris
GeneralRe: Just One SubsussAnonymous17 Jan '04 - 6:29 
Simple and elegant. Very nice solution. Cool | :cool:
GeneralRe: Just One Submemberaah_what1 Jul '04 - 20:48 
Hi,
 
Is there a way that I can make it so that it will ignore a keypress if the item is not found?
 
Thanks
 
Matt
GeneralRe: Just One Submembermikah_9721 Sep '04 - 14:02 
Did anybody answer this? Smile | :)
GeneralRe: Just One SubsussAnonymous21 Sep '04 - 20:47 
Not yet,
 
Do you know how to do this / build a real cool autocomplete combo?
 
Cheers,
 
Matt
GeneralRe: Just One SubmemberAlejandro K.28 Sep '04 - 7:50 
I got a solution... for how to ignore the keypress if the text was not found...
 
instead of
 
.....
If Index = -1 Then Index = .FindString(ToFind)
If Index = -1 Then Return
.....
 
u can use:
 
....
If Index = -1 Then Index = .FindString(ToFind)
If Index = -1 Then
e.Handled = True
Return
end if

.....
 

Hope it helps.
Alex.
GeneralRe: Just One SubmemberM@@N29 Sep '04 - 3:35 
I would like to have something like this:
- when i type a value in the combobox, i only want to see the values that start with that value and the other values aren't visible
 
is this possible??
GeneralRe: Just One SubsussAnonymous19 Sep '05 - 13:18 
This is working for me except when I tab off of the control the text appears correct in the combobox but the cbo.text has a value of the text of the last selected item and that items selectedindex. The same things happens when if I use back space in the combobox and then tab off of the control.
GeneralRe: Just One SubmemberDaniel8c26 Mar '06 - 17:05 
1st of all, you need to set the FormattingEnabled Property of the combobox to TRUE. then
you have to add 1 more line in your code before you can use the updated combobox selectedindex:
 
Combobox1.SelectedIndex = Combobox1.FindStringExact(ComboBox.Text)
 
Tested under .Net 2.0

GeneralRe: Just One Subsussaniepras30 Dec '04 - 7:22 
freakin awesome

GeneralRe: Just One SubsussAnonymous27 Mar '05 - 13:41 
Just what the doctor ordered. Fabulous. Smile | :)
GeneralRe: Just One SubmemberLaurent Muller27 Mar '05 - 23:09 
Thank You !Big Grin | :-D
GeneralRe: Just One Submemberquick_dry3 Aug '05 - 23:02 
this seemed to work a treat, but the only value I could get out of the combobox was .Text, I could not get .SelectedValue to update unless I actually clicked the entry in the combobox (when using a databound combobox)
any clues?

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

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