Error, Loop when pressing ENTER with e.Keycode

Asked

Viewed 113 times

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 be empty:

   private void btnEmgSearch_Click(object sender, EventArgs e)
    {

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

Ok

When the MessageBox appears and I press the key ENTERto give the OK Popup system considers a new ENTER and gets back into the routine txtEmgSearch_KeyUp. and so I stay in a loop until I click on OK with the Mouse.

Some way to fix it ??

1 answer

4


The problem is that both Messagebox and Textbox are responding to the event. Try using Keydown instead of Keyup.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.