Results 1 to 3 of 3

Thread: [2.0] Capture "Enter" from Text box

  1. #1

    Thread Starter
    Addicted Member jordan23's Avatar
    Join Date
    Dec 2002
    Posts
    166

    [2.0] Capture "Enter" from Text box

    I have done this before in VB6, but cannot figure out how to do it in C#. I want to add code so that when the user types in the textbox, that they can hit enter after they are done and it will call the button1_click event without them having to move the mouse and click it. Thanks in advance.

  2. #2
    PowerPoster 2.0 Negative0's Avatar
    Join Date
    Jun 2000
    Location
    Southeastern MI
    Posts
    4,367

    Re: [2.0] Capture "Enter" from Text box

    You need to set KeyPreivew = true on the form:

    Code:
            private void Form1_Load(object sender, EventArgs e)
            {
                this.KeyPreview = true;
                
            }
    
            private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (e.KeyChar == 13)
                {
                    button1_Click(button1, EventArgs.Empty);
                }
            }

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2.0] Capture "Enter" from Text box

    Firstly, is you just assign that Button to the AcceptButton property of the form then it will be automatically clicked when the user presses Enter, as long as the selected control doesn't capture the Enter key itself. A standard TextBox does NOT capture the Enter key, so this will work.

    Secondly, if you're handling an event of the TextBox as -0 has suggested then the form's KeyPreview property is irrelevant. It's only if you're handling an event of the form that that matters. If you want to trap the Enter key no matter the selected control, THEN you should handle an event of the form.

    Finally, I'd suggest handling the KeyDown event and looking for (e.KeyCode == Keys.Enter) in preference to the KeyPress event.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width