简体   繁体   English

将文本框的_KeyDown事件连接到按钮控件的_click事件

[英]Wire _KeyDown event of textbox to a _click event of button control

I have a form with a textbox called 'tbWO.' 我有一个带有名为“ tbWO”的文本框的表单。 This field is used to enter a Purchase Order Number. 此字段用于输入采购订单编号。 I also have a button control called 'btnFill.' 我还有一个名为“ btnFill”的按钮控件。 When btnFill is clicked, it fills a dataset with a parameter from 'tbWO.' 单击btnFill时,它将使用'tbWO'中的参数填充数据集。

I would like to be able to press 'ENTER' in the 'tbWO' textbox (after a Purchase Order # is entered) and have it fire the btnFill_Click event I mentioned above. 我希望能够在“ tbWO”文本框中按“ ENTER”(输入采购订单编号后),并触发我上面提到的btnFill_Click事件。

I tried with this bit of errant, badly written code - but, it's just not working properly, ie, at all, or how I think it should work. 我尝试了一些错误的,编写错误的代码-但是,它只是无法正常工作,即根本无法工作,或者我认为它应该如何工作。 Anyway, the code is below; 无论如何,下面的代码; in all it's glory. 在所有的荣耀。

        private void txtWO_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            btnFill.Click += new EventHandler(btnFill_Click);
        }
    }

I will admit confusion on using 'new EvenHandler( ?? ). 我将对使用'new EvenHandler(??)造成混淆。 Fairly new to C# (as is probably blantantly obvious.) 对C#来说还算是新手(可能显而易见)。

Any help, links, suggestions - all are greatly appreciated. 任何帮助,链接,建议-都将不胜感激。

Thanks. 谢谢。

Jasoomian 茉莉花

you could do this... 你可以这样做...

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

As a rule, I abhor mapping one event handler to another. 通常,我讨厌将一个事件处理程序映射到另一个事件处理程序。 Instead, write a separate function, and have both event handlers invoke that separate function. 而是编写一个单独的函数,并使两个事件处理程序都调用该单独的函数。 Something like this: 像这样:

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

private void btnFill_Click(object sender, EventArgs e)
{
    AcceptInput();
}

private void AcceptInput()
{
    // Do clever stuff here when the user presses enter 
    // in the field, or clicks the button.
}

Granted, you may feel differently, but it accomplishes the same thing, but with (IMO) far more readable code. 当然,您可能会有所不同,但是它完成了同一件事,但是(IMO)的代码可读性强得多。 But it's been my experience that criss-crossing event handlers is very sloppy and leads to maintenance headaches out the wazoo. 但是根据我的经验,纵横交错的事件处理程序非常草率,导致维护麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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