Press enter in textbox to and execute button command

前端 未结 10 695
时光取名叫无心
时光取名叫无心 2021-01-30 13:40

I want to execute the code behind my Search Button by pressing Enter. I have the Accept Button property to my search button. However, when i place my button as NOT vi

相关标签:
10条回答
  • 2021-01-30 13:55

    You can handle the keydown event of your TextBox control.

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

    It works even when the button Visible property is set to false

    0 讨论(0)
  • 2021-01-30 13:58

    There are some cases, when textbox will not handle enter key. I think it may be when you have accept button set on form. In that case, instead of KeyDown event you should use textbox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)

    0 讨论(0)
  • 2021-01-30 13:59

    there you go.

    private void YurTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                YourButton_Click(this, new EventArgs());
            }
        }
    
    0 讨论(0)
  • 2021-01-30 14:02

    If buttonSearch has no code, and only action is to return dialog result then:

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                DialogResult = DialogResult.OK;
        }
    
    0 讨论(0)
  • 2021-01-30 14:05
        private void textbox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //cod for run
            }
        }
    
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            textbox1_KeyDown(sender, new KeyEventArgs(Keys.Enter));
        }
    
    0 讨论(0)
  • 2021-01-30 14:07

    You could register to the KeyDown-Event of the Textbox, look if the pressed key is Enter and then execute the EventHandler of the button:

    private void buttonTest_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Hello World");
    }
    
    private void textBoxTest_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            buttonTest_Click(this, new EventArgs());
        }
    }
    
    0 讨论(0)
提交回复
热议问题