Error, Loop when pressing ENTER with e.KeyCode

3

I'm trying this code:

   private void txtEmgSearch_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            this.btnEmgSearch.PerformClick();
        }
    }

The command itself works normally, but there is a IF if the txtEmgSearch is empty:

   private void btnEmgSearch_Click(object sender, EventArgs e)
    {

        if (txtEmgSearch.Text == "")
        {
            MessageBox.Show("Insert part#!");
            return;
        }
     ...

When MessageBox appears and I press ENTER to give OK of PopUp the system considers a new ENTER and re-enters the txtEmgSearch_KeyUp routine. and so I stay in a Loop, until I click on OK with the Mouse.

Any way to solve this ??

    
asked by anonymous 23.09.2016 / 22:06

1 answer

4

The problem is that both the MessageBox and the TextBox are responding to the event. Try to use the KeyDown event instead of the KeyUp.

private void txtEmgSearch_KeyDown(object sender, KeyEventArgs e) {
    if (e.KeyCode == Keys.Enter) {
        this.btnEmgSearch.PerformClick();
        e.SuppressKeyPress = true;
    }
}
    
23.09.2016 / 22:18