tags:

views:

54

answers:

2

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.

+1  A: 

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;
        }
    }
Hans Passant
But this is my problem, i dont want it to trigger both, i want it to trigger only the MessageBox button
WoF_Angel
@WoF: I'd better spell it out. Post updated.
Hans Passant
It worked, thanks man
WoF_Angel
Comment out the SuppressKeyPress assignment to learn more.
Hans Passant
Not sure what you mean by comment out, but now that you mentioned it, what does SuppressKeyPress does? Maybe it stops multiple events from firing when holding the button down? just guessing
WoF_Angel
A: 

Controls will only fire events if they have focus. So in your case you're executing button click with focus still on your text box and that's why you can't use enter on the message box. The solution is to add following code inside button1_Click method:

var btn = sender as Button;
btn.Focus();

This time focus will be set on the button so if you hit enter on the message box no event will fire for text box

tchrikch
I can use enter the message box. In fact, what i want is to use enter ONLY in the MessageBox, not in BOTH the MessageBox and my button
WoF_Angel
Okay , but what I was trying to say is that with setting focus on the button you can use enter on your message box and it will not trigger text box event again and again
tchrikch