AutoComplete

Introduction

This is a simple code snippet which is used to make an Auto Complete ComboBox.

Using the code

Usage: Call the subroutine from within the ComboBox’s KeyPress event handler.

   1: AutoComplete(ByRef cb As ComboBox, _
   2:     ByVal e As System.Windows.Forms.KeyPressEventArgs, _
   3:     Optional ByVal blnLimitToList As Boolean = False)

  • cb – ComboBox used to make the Auto Complete ComboBox.
  • eSystem.Windows.Forms.KeyPressEventArgs used to handle the keyboard inputs.
  • blnLimitToList – Optional Boolean value indicating whether the user input is limited to the list values or not.

Code

   1: ' AutoComplete
   2:  
   3: Public Sub AutoComplete(ByRef cb As ComboBox, _
   4:     ByVal e As System.Windows.Forms.KeyPressEventArgs, _
   5:     Optional ByVal blnLimitToList As Boolean = False)
   6:  
   7:   Dim strFindStr As String
   8:  
   9:   If e.KeyChar = Chr(8) Then 'Backspace
  10:  
  11:       If cb.SelectionStart <= 1 Then 
  12:           cb.Text = ""
  13:           Exit Sub
  14:       End If
  15:       If cb.SelectionLength = 0 Then
  16:           strFindStr = cb.Text.Substring(0, 
  17:                            cb.Text.Length - 1)
  18:       Else
  19:           strFindStr = cb.Text.Substring(0, 
  20:                         cb.SelectionStart - 1)
  21:       End If
  22:   Else
  23:       If cb.SelectionLength = 0 Then
  24:           strFindStr = cb.Text & e.KeyChar
  25:       Else
  26:           strFindStr = cb.Text.Substring(0, 
  27:                 cb.SelectionStart) & e.KeyChar
  28:       End If
  29:   End If
  30:  
  31:   Dim intIdx As Integer = -1
  32:  
  33:   ' Search the string in the Combo Box List.
  34:  
  35:   intIdx = cb.FindString(strFindStr)
  36:  
  37:   If intIdx <> -1 Then ' String found in the List.
  38:  
  39:       cb.SelectedText = ""
  40:       cb.SelectedIndex = intIdx
  41:       cb.SelectionStart = strFindStr.Length
  42:       cb.SelectionLength = cb.Text.Length
  43:       e.Handled = True
  44:   Else
  45:       If blnLimitToList = True Then
  46:           e.Handled = True
  47:       Else
  48:           e.Handled = False
  49:       End If
  50:   End If
  51: End Sub

 

History

  • Released on July 30th, 2005.