for my combobox i want to prevent user from typing further text if the typed text do not match part of combobox items i.e from starting

Autocomplete mode set to SuggestAppend
Autocompletesource set ot Listitems

  Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
    Dim i As Integer   
    For i = 0 To ComboBox1.Items.Count - 1
     'required code
     e.Handled = True      
    Next i
    End Sub

Recommended Answers

All 8 Replies

Try this :

Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
    If CType(sender, ComboBox).FindString(CType(sender, ComboBox).Text, 1) = True Then
        'if it doesnt exist then remove the last character/s that dont match and set the cursor position to the end
        CType(sender, ComboBox).Text = CType(sender, ComboBox).Text.Substring(0, CType(sender, ComboBox).Text.Length - 1)
        CType(sender, ComboBox).SelectionStart = CType(sender, ComboBox).Text.Length

        e.Handled = True

        ' accepting backspase
        If Asc(e.KeyChar) = 8 Then
            e.Handled = False
        End If
    End If
End Sub

it works but last charecter is displyed until next key is pressed and SuggestAppend goes off

when backspace is pressed 2 last cherecters get deleted.

can the last charecter be blocked from displayed so that no need of backspace and SuggestAppend remain active.

Try this

Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress

    Dim cbx As ComboBox = sender
    e.Handled = cbx.FindString(cbx.Text & e.KeyChar, 1) = -1 And Asc(e.KeyChar) <> 8

End Sub

although there are still ways to screw it up. For example, if one of the acceptable words is "aardvark" and you enter "aardv" then cursor left twice and delete a character you will end up with a typed entry that does not match any word in the list. You'd have to add code to handle this or disable cursor keys.

it dosen work the way i wanted

i want result as per below code which i used in VB6 http://www.visualbasic.happycodings.com/Forms/code39.html

i tried to convert it in vb.net but getting some errors can u help me to convert this or change your suggession to achive this result.

Make a Combo Box Auto Complete

If you want you VB Combo boxes to automatically complete then use the following
code:

'API call (add to declaration section of form or module)

Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

'Purpose : Auto completes a combo box during the KeyPress event, based on the text typed in by the user.
'Inputs : cboComplete The combo box to auto complete (completes the current text based on
' the listitems in the combo).
' KeyAscii The Ascii value of the key pressed (as supplied by the keypress event)
' [bLimitToList] If True, will only allow the user to enter values which are in the combos list.
'Outputs : Returns the KeyAscii value or zero if bLimitToList = True and the user types an invalid character.
'Notes : Call the routine from the _KeyPress event of the combo.
' The combo must be of a vbComboDropDown style, eg. KeyAscii = ComboAutoComplete(Combo1, KeyAscii, False)

Public Function ComboAutoComplete(ByRef cboComplete As ComboBox, ByVal KeyAscii As Integer, Optional ByVal bLimitToList As Boolean = False) As Long
    Dim lRetVal As Long
    Dim sSearch As String
    Const CB_ERR = (-1), CB_FINDSTRING = &H14C

    On Error GoTo ErrFailed
    If cboComplete.Style <> vbComboDropdown Then
        Debug.Print "Error in ComboAutoComplete. Combo must be of the style vbComboDropdown..."
        Debug.Assert False
        'Return the KeyAscii
        ComboAutoComplete = KeyAscii
        Exit Function
    End If

    If KeyAscii = 8 Then
        'Pressed delete
        If cboComplete.SelStart <= 1 Then
            'Last character, clear combo.
            cboComplete.Text = ""
            ComboAutoComplete = 0
            Exit Function
        End If
        'Delete text
        If cboComplete.SelLength = 0 Then
            'Delete a single character
            sSearch = UCase$(Left$(cboComplete.Text, Len(cboComplete) - 1))
        Else
            'Delete the selected text
            sSearch = Left$(cboComplete.Text, cboComplete.SelStart - 1)
        End If
    ElseIf KeyAscii < 32 Or KeyAscii > 127 Then
        'Invalid keyboard characters
        Exit Function
    Else
        'Append the new text to the combo text
        If cboComplete.SelLength = 0 Then
            'Append a character
            sSearch = UCase$(cboComplete.Text & Chr$(KeyAscii))
        Else
            'Insert a character
            sSearch = Left$(cboComplete.Text, cboComplete.SelStart) & Chr$(KeyAscii)
        End If
    End If
    'Find the closest match
    lRetVal = SendMessage(cboComplete.hwnd, CB_FINDSTRING, -1, ByVal sSearch)

    If lRetVal = CB_ERR Then
        'Did not find a matching item in list
        If bLimitToList = True Then
            'Block the KeyAscii
            ComboAutoComplete = 0
        Else
            'Return the KeyAscii
            ComboAutoComplete = KeyAscii
        End If
    Else
        'Found a matching item in list
        cboComplete.ListIndex = lRetVal
        cboComplete.SelStart = Len(sSearch)
        cboComplete.SelLength = Len(cboComplete.Text) - cboComplete.SelStart
        ComboAutoComplete = 0
    End If

    Exit Function

ErrFailed:
    'Return the keycode
    ComboAutoComplete = KeyAscii
End Function


'Demonstration:

'To call the ComboAutoComplete routine, place the following code in the form in the combo keypress event.

Private Sub Combo1_KeyPress(KeyAscii As Integer)
    KeyAscii = ComboAutoComplete(Combo1, KeyAscii, False)
End Sub

Make autocomplete of combobox is different thing with prevent user input in combobox.
You drag us with preventing user input but actualy you want to make autocomplete of combobox.
VB6 and VB.Net has different way to make autocomplete. Autocomplete is an easy task in vb.net.

Here is the vb.net ways :

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim MySource As New AutoCompleteStringCollection
    MySource.AddRange(New String() {"Monday", "Thursday", "Wednesday", "Tuesday", "Friday"})

    ComboBox1.AutoCompleteCustomSource = MySource
    ComboBox1.AutoCompleteMode = AutoCompleteMode.Suggest
    ComboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource
End Sub

If you use my suggested code along with AutoComplete set to Suggest and AutoCompleteSource set to ListItems you will get what you want. You can also try the two other AutoCompleteModes to see if that action suits you better.

i have already set Autocomplete properties to SuggestAppend and Autocompletesource ot Listitems

i want to prevent user from typing further text if the typed text do not match part of combobox items.

Your first suggestion was ok but it keeps the last unmatched character until next key is pressed and removes last two characters when next key is pressed. Also if you click somewhere else the unmatched text remains on combo box. I don’t want to display the last unmatched character at all (exactly as done in your second suggestion) and SuggestAppend should remain active.

In your second suggestion it blocks the unmatched character from displaying but has to press twice the next character to filter and shorten suggested list.

also When focus is moved somewhere else unmatched text should not remain on combobox .

Your first suggestion was ok but it keeps the last unmatched character until next key is pressed

Not on my computer. On my computer non-matching keys are ignored. Unmatched keys are never displayed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.