Craig
Craig

Reputation:

Using Keypress to Add Item to Listbox

I have a textbox and a listbox and I'd like to have the listbox add an item (based on textbox) when enter is pressed.

I am using vb 2008

Please help, I am struggling lol. Thanks!

Upvotes: 2

Views: 2449

Answers (3)

FalconXSoftware
FalconXSoftware

Reputation: 21

Try this:

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles 
    TextBox1.KeyDown
    Me.ListBox1.Items.Add(TextBox1.Text)
End Sub

Upvotes: 2

Bored1
Bored1

Reputation: 11

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
    If e.KeyCode = Keys.Enter Then
        ListBox2.Items.Add("Misc. - " & TextBox1.Text)
        TextBox1.Clear()
    End If
End Sub

Upvotes: 1

Kredns
Kredns

Reputation: 37211

Just create a method like so:

void AddItemToListBox(string item)
{
    lstMyList.Items.Add(item);
}

Then hook this up to the key down event of the text box for when the Enter key is pressed:

private void textBox1_KeyDown(object sender, KeyEventArgs e) 
{
    if (e.KeyCode == Keys.Enter) 
    {
        AddItemToListBox(textBox1.Text);
    }
}

Upvotes: 2

Related Questions