System: Windows7 Pro, Visual Studio 2010, C#
I have a textbox: textBox1
I set its event:
textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1.PerformClick();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Invalid data", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
It works fine, the problem is, when the data entered is invalid, and thus the MessageBox
is shown, when i hit ENTER on the MessageBox
OK Button, it also triggers the textBox1_KeyUp
, which causes the MessageBox
to show up again.
So, it triggers the MessageBox
OK button, which causes it to disappear, and also triggers the textbox_keyUp
which then causes the messagebox to show up again.
Thanks for your help.
Yes, the message box responds to the key down event. So should your TextBox. Use the KeyDown event instead, problem solved. Also solves the annoying BEEP the user normally hears.
private void textBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyData == Keys.Enter) {
button1.PerformClick();
e.SuppressKeyPress = true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With