views:

371

answers:

4

When the user is entering a number into a text box, I would like them to be able to press Enter and simulate pressing an Update button elsewhere on the form. I have looked this up several places online, and this seems to be the code I want, but it's not working. When data has been put in the text box and Enter is pressed, all I get is a ding. What am I doing wrong? (Visual Studio 2008)

private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        btnMod.PerformClick();
    }
}
+1  A: 

A few thoughts:

  • does the form have an accept-button (set on the Form) that might be stealing ret
  • does the textbox have validation enabled and it failing? try turning that off
  • does something have key-preview enabled?
Marc Gravell
a) Nopeb) I'm validating input within the _Click function using int32.tryparse, but that's only after the Click event happens. I tried commenting the entire function out and just putting in a MessageBox and it still didn't work.3) Looked on the form control - key preview is off. I also went through the next four responses below. Nothing seems to do the trick so far.
Michael Hermes
A: 

form properties > set KeyPreview to true

Paul Creasey
A: 

Set e.Handled to true immediately after the line

btnMod.PerformClick();
.

Hope this helps, Best regards, Tom.

tommieb75
A: 

Are you sure the click on the button isn't performed ? I just did a test, it works fine for me. And here's the way to prevent the "ding" sound :

private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        btnMod.PerformClick();
        e.SuppressKeyPress = true;
    }
}
Thomas Levesque