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.
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)
recRowView = cboName.SelectedItem
If recRowView Is Nothing Then Exit Sub
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
Select Case e.KeyCode
Case Keys.Back, Keys.Left, Keys.Right, Keys.Up, Keys.Delete, Keys.Down
Return
End Select
sTypedText = cbo.Text
iFoundIndex = cbo.FindString(sTypedText)
If iFoundIndex >= 0 Then
oFoundItem = cbo.Items(iFoundIndex)
sFoundText = cbo.GetItemText(oFoundItem)
sAppendText = sFoundText.Substring(sTypedText.Length)
cbo.Text = sTypedText & sAppendText
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