Mike S
Mike S

Reputation: 7

Filling a listbox from a textbox without using a button or click event in VB

I'm not sure if it is possible, but I would like to know if a listbox can be updated by adding or removing text by typing that text into a textbox without using a button event or some type of click event. I've tried using the text_changed event but it inserts the text as I type so I am unable to type an entire string and then move that into a listbox as a whole string.

What I am trying to do is scan a magnetic ID card through a reader and have it insert the data from that card into a listbox and when I scan the same card again, it will remove the data. This is for an employee logging system.

Thanks.

Upvotes: 0

Views: 425

Answers (1)

Blackwood
Blackwood

Reputation: 4534

With the following code, if you type a string in TextBox1 and hit Enter, we check to see if the string already exists in ListBox1. If so, the string is removed from the ListBox, otherwise it is added. Then TextBox1 is cleared.

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    If e.KeyChar = vbCr Then
        If ListBox1.Items.Contains(TextBox1.Text) Then
            ListBox1.Items.Remove(TextBox1.Text)
        Else
            ListBox1.Items.Add(TextBox1.Text)
        End If
        TextBox1.Clear()
        e.Handled = True
    End If
End Sub

Upvotes: 1

Related Questions