Hello all!

I am trying to add to items to a combobox by using the "enter" key. It does work when I add the first item, but if I manually clear the box and add another items it does not get added to the list.

(1) I click in the combobox and type "hello" and press the "enter" key
(2) I click on the dropdown arrow and see that "hello" is in the list
(3) I select "hello" in the box and erase it, item is still in the list
(4) I type "goodbye" in the box and press the "enter" key
(5) "hello" is still in the list but "goodbye" is not

Here is the code:

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

If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then

Dim CopyrightVar As String
CopyrightVar = CopyrightCombo.Text
CopyrightCombo.Items.Add(CopyrightVar)
CopyrightCombo.Update()
e.Handled = True

End If

End Sub

Funny thing, if I comment the if/end if line and type "hello" the items added to the combobox list are: "h", "he", "hel", "hell", "hello" wich makes sens since the add items is run on every keypress :)

So: I know that my commands for adding items is good, I know that my keypress event is handled properly but not when I specify using the "enter" key. Darn.

Being a newbie I am missing something for sure. Hope someone can help :)

very finny and solution is also very for this try keydown event

Private Sub ComboBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyDown
        If e.KeyCode = Keys.Enter Then
            ComboBox1.Items.Add(ComboBox1.Text)
            ComboBox1.Text = ""
        End If
    End Sub

Ho well :) it works! Now I need to understand the difference between keypress and keydown as, to me it should produce the same result. I read that I should use "keyup" so that if the user press the key and leaves it pressed it does not generate multiple entries. I change my code to:

Private Sub CopyrightCombo_Keyup(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles CopyrightCombo.KeyUp

If e.KeyCode = Keys.Enter Then

Dim CopyrightVar As String
CopyrightVar = CopyrightCombo.Text
CopyrightCombo.Items.Add(CopyrightVar)
CopyrightCombo.Update()

End If
End Sub

Thanks for your help !!

mark your thread as solved.

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.