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
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
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.
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 = "";
}
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);
}
}
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.