Introduction
I got the basic idea of developing an AutoComplete Sub for a combobox from MSDN and I have edited the code and here is the
result. This sub is much more professional and flexible to use. The code is
commented and includes details on using the code.
Code Listing
Module Module1
Public Sub AutoComplete(ByVal cbo As ComboBox, _
ByVal e As System.Windows.Forms.KeyEventArgs)
Dim iIndex As Integer
Dim sActual As String
Dim sFound As String
Dim bMatchFound As Boolean
If Not cbo.Text = "" Then
If e.KeyCode = Keys.Back Then
cbo.Text = Mid(cbo.Text, 1, Len(cbo.Text) - 1)
End If
If ((e.KeyCode = Keys.Left) Or _
(e.KeyCode = Keys.Right) Or _
(e.KeyCode = Keys.Up) Or _
(e.KeyCode = Keys.Down) Or _
(e.KeyCode = Keys.PageUp) Or _
(e.KeyCode = Keys.PageDown) Or _
(e.KeyCode = Keys.Home) Or _
(e.KeyCode = Keys.End)) Then
Return
End If
Do
sActual = cbo.Text
iIndex = cbo.FindString(sActual)
If (iIndex > -1) Then
sFound = cbo.Items(iIndex).ToString()
cbo.SelectedIndex = iIndex
cbo.SelectionStart = sActual.Length
cbo.SelectionLength = sFound.Length
bMatchFound = True
Else
If sActual.Length = 1 Or sActual.Length = 0 Then
cbo.SelectedIndex = 0
cbo.SelectionStart = 0
cbo.SelectionLength = Len(cbo.Text)
bMatchFound = True
Else
cbo.SelectionStart = sActual.Length - 1
cbo.SelectionLength = sActual.Length - 1
cbo.Text = Mid(cbo.Text, 1, Len(cbo.Text) - 1)
End If
End If
Loop Until bMatchFound
End If
End Sub
End Module