C# - Pushing Enter in MessageBox triggers control KeyUp Event

Viewed 11800

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.

3 Answers
Related