954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to add content of a Textbox to Listbox upon pressing the enter key?

Hi

I have a textbox and a listbox.
If i write something into the textbox and press the enter key, i would like the content of the textbox to appear in the listbox. What is the best way to do it?

Thanks in advance

vivek4020
Newbie Poster
18 posts since Nov 2009
Reputation Points: 10
Solved Threads: 0
 

create a event handler for KeyDown for the textbox. then in the method add

if (e.KeyCode == Keys.Enter)
            {
                listbox1.Items.Add(textBox1.text);
            }


substitute the listbox1 for the correct name, and textbox1 for the appropriate name as well.

Diamonddrake
Master Poster
724 posts since Mar 2008
Reputation Points: 442
Solved Threads: 89
 

Well you can try this as well:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
                addItemToList();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            addItemToList();
        }

        private void addItemToList()
        {
            if (textBox1.Text.Length==0)
                return;

            listBox1.Items.Add(textBox1.Text);
            textBox1.Text = "";
        }
avirag
Posting Whiz
313 posts since Jun 2009
Reputation Points: 31
Solved Threads: 36
 

Using the KeyDown event of the text box for capturing Enter isn't always safe. If the form has a DefaultButton set then the button will receive the Enter key press, and the textbox event will never fire. What you can do is override ProcessCmdKey() :

private void frmTestKeyDown_Load(object sender, EventArgs e)
    {
      this.AcceptButton = button1;
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
      if (((keyData & Keys.Enter) == Keys.Enter) && this.textBox1.Focused)
      {
        listBox1.Items.Add(textBox1.Text);
        return true; //stops the key from being further processed
      }
      else
      {
        return base.ProcessCmdKey(ref msg, keyData);
      }
    }
sknake
Industrious Poster
4,954 posts since Feb 2009
Reputation Points: 1,764
Solved Threads: 735
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: