Search code examples
c#winformskeypress

I'm trying to call a method from a textbox in winforms when the enter key is pressed and it's not working


The if statement is being checked until I hit enter then it goes straight to another method. My guess is there is something else on the form that is getting triggered when I hit enter but I can't find it despite my search. I want to not have to put a button on the form to call this function, the button I had worked but I just want to be able to hit enter from my textbox input.

Here is my code below:

 private void textBox1firstName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                searchAD();
            }
        }

        private void textBox2lastName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                searchAD();
            }

        }

searchAD() is not getting called despite hitting enter. Any suggestions? Thank you!


Solution

  • The form has a KeyDown event, but also has a "AcceptButton" property, which hooks the [Enter] keypress and can call an event handler. Check if there are event-handlers attached to either of those on the form.