TextChanged sends a notification for every key press inside the TextBox control.
Should I be using KeyDown event?
TextChanged sends a notification for every key press inside the TextBox control.
Should I be using KeyDown event?
Yep, in the keydown event:
if (e.KeyCode == Keys.Enter)
{
// do stuff
}
The KeyPress event works for this:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
MessageBox.Show("Enter pressed!");
}
}
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;