Frank Wittich
Frank Wittich

Reputation: 139

KeyDown event is not firing when pressing enter in an UserControl

I have a UserControl for an application and with a textbox. When pressing enter in this textbox a button should be activated (basically pressing 'Ok' via pressing Enter instead of clicking the button manually with the mouse).

So I added a KeyDown event to my textbox and implemented the following code:

private void txtSearchID_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter && !txtSearchID.Text.Equals(string.Empty))
    {
       button_Click(null, null);
    }
}

But when I wanted to test this nothing happened when pressing Enter. Strangely enough in addition to that the event does not even get fired when pressing Enter but with every other key. Am I missing something?

Upvotes: 2

Views: 4864

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222720

This is because, when a key is pressed it will go to the control which has focus on the form, as the KeyPreview property of Form is set to False by default. You change the event like this

Change to KeyUP event,

private void txtSearchID_Keyup(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter && !txtSearchID.Text.Equals(string.Empty))
    {
       button_Click(null, null);
    }
}

Upvotes: 10

Related Questions