How to Add Item in ListBox Control from TextBox - Visual Basic 2017

Hot

Monday, October 16, 2017

How to Add Item in ListBox Control from TextBox

First create a form similar to the picture bellow!
How to Add Item in ListBox Control

- 1 TextBox control
- 1 Button
- 1 ListBox control

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListBox1.Items.Add(TextBox1.Text)
    End Sub

We can polish this code by adding a code to clear the content in the TextBox control after pressing the button and focusing the TextBox.

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListBox1.Items.Add(TextBox1.Text)

        TextBox1.Clear()
        TextBox1.Select()
    End Sub

Probably you noticed that I used the code TextBox1.Select() to focus the cursor onto the TextBox control. This is because in Visual Basic 2017 you can't set focus on a Windows Form TextBox control.

No comments:

Post a Comment