Pregunta

I have Windows Form Application with TextBox and Label and I want to type something in the textbox and then press Enter to let's say show what I've typed in Label.

Example with button:

private void button1_Click(object sender, EventArgs e)
    {            
        this.Label1.Text = this.TextBox1.Text;
    }

I need to do exactly the same but with pressing Enter not button.

¿Fue útil?

Solución

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

Otros consejos

I tried the code from Jan Anderssen and it works correctly. The error "Operator '==' can not be applied to operands of type 'char' and 'System.Windows.Forms.Keys" is because you are matching a character to Keys.Enter, make sure that the syntax is correct e. KeyCode.

E.KeyCode is used because in the event handler send a parameter with the value of e "KeyEventArgs e" variable and here is the key pressed.

private void txtText_KeyDown (object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter) 
{
this.lblText.Text = this.txtText.Text;
}
}

Did you copy and paste the code?

If so, try doing it with the events of the properties box. Click in the textbox -> Events ---> key down ---> double click and put the code there.

Do you have more than one form? This code may change.

you can use the text change event and check when enter pressed. when you identify enter, then you can do what ever you want

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top