How to fire the Click event of a button by hitting Enter in a Text

G

Guest

I have a single button on my form, and when I press the Enter key while a
TextBox has focus I want the Button.Click event to fire.

Is there a simple way to do this ?
 
C

Craig Lister

New to this myself, but surely the 'KeyPress' event.. you can detect if the
keypress was an enter, and then Button.click();
 
O

O.S. de Zwart

You can call the event handler by calling something like
this.button1_Click(this.button1, null); from the textbox Keypress
eventhandler if the KeyChar value of the KeyPressEventArgs e is equal to
(char)13. However you might want to consider not placing the code to
be executed in the event handler itself but instead in a private method
and call that method from both the button Click and textbox Keypress
events. This concept can be extended by using the Command design pattern
which I have found leads to much cleaner code in winform applications.
For more information about the Command design pattern see:
http://www.dofactory.com/Patterns/PatternCommand.aspx

Regards,

Olle
 
A

Alexander

Create an onkeypress event on the button. When catched check which
button is pressed and if its the enter button call the 'button1_Click'
method.

For example

private void button1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == (char) 13)
{
this.button1_Click(sender, new EventArgs());
}
}
 
C

carion1

Set the forms .AcceptButton to the button you want. You may also want to
make use of .CancelButton.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top