Joan Venge
Joan Venge

Reputation: 331330

What event to use for a TextBox control to signal text change upon pressing enter?

TextChanged sends a notification for every key press inside the TextBox control.

Should I be using KeyDown event?

Upvotes: 2

Views: 3222

Answers (5)

Henk Holterman
Henk Holterman

Reputation: 273571

It depends on the rest of your Form. When you have an Accept Button, [Enter] in (almost) any control will trigger that button and it would be best to stay away from handling it separate in Textboxes.

Reversely, if you do want to handle it one or more Textboxes, don't use an Accept Button.

Upvotes: 1

JaredPar
JaredPar

Reputation: 755259

The better event to handle here is KeyDown. KeyDown will fire when the user explicitly types into the box or another components simulates users typing by sending messages to the TextBox. This fits the scenario you described.

If on the other hand you choose to respond to the TextChanged event, you will be responding to every occasion where the text is changed (by user or by code). This means that your event will be raised if I explicitly say

someBox.Text = Environment.NewLine;

Upvotes: 5

Michael Petrotta
Michael Petrotta

Reputation: 60942

The KeyPress event works for this:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter)
    {
        MessageBox.Show("Enter pressed!");
    }
}

Upvotes: 2

Jeremy Morgan
Jeremy Morgan

Reputation: 3372

Yep, in the keydown event:

if (e.KeyCode == Keys.Enter)
{
   // do stuff
}

Upvotes: 8

Related Questions