简体   繁体   中英

Make a button to be clicked when enter is pressed in any textbox

I have a panel that looks like this: 面板图片

Here the user can edit the database when he clicks update.

I want to make it able to work when the user is pressing Enter.

so I could use this code for each textbox's KeyUp Event:

 private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            button1_Click(this, new EventArgs());
            //Added this so there is no sound when Enter is pressed.
            e.SuppressKeyPress = true;
        }
    }

My question is, can I do it without having to add this code for every textbox event separately? Can I group some textboxes events together?

You make button1 (please give it a better name) be the AcceptButton of the form

//in constructor, after InitializeComponent
this.AcceptButton = button1;

Note that if the currently focused control consumes the return key for some reason (Buttons consume it and click themselves, multi line textboxes consume it and start a new editing line)) then your button1 won't be clicked

You can also attach the same event handler code to multiple events/on multiple controls , so you could have one method:

void AnyTextbox_KeyPress(...){ 
  if( it's the return key ) 
    ...
}

And as well as any keypress you have wired up in the designer you can do(again in the constructor):

nameTextbox.KeyPress += AnyTextbox_KeyPress;
ageTextbox.KeyPress += AnyTextbox_KeyPress;
addressTextbox.KeyPress += AnyTextbox_KeyPress;

And pressing a key in any of these text boxes will fire this event handler plus any other event handler also connected to that box's KeyPress

Think of an event as like a List of Methods, and when an event occurs C# will work it's way through the list calling each of the methods. If you attached 100 different handlers to an event with 100 uses of +=, they would all be called

Note that the order in which they fire should not be relied upon. Do not write code in one event handler that relies on code in another event handler being run first. Later added event handlers do not necessarily fire after earlier added event handlers

you can simply make one function for the below code and call that function in all your click events

 private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            button1_Click(this, new EventArgs());
            //Added this so there is no sound when Enter is pressed.
            e.SuppressKeyPress = true;
        }
    }

eg textBox1_KeyDown(sender,e) in where ever you want to call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM