views:

60

answers:

2

I have a form with a textbox called 'tbWO.' This field is used to enter a Purchase Order Number. I also have a button control called 'btnFill.' When btnFill is clicked, it fills a dataset with a parameter from '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.

I tried with this bit of errant, badly written code - but, it's just not working properly, i.e., 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( ?? ). Fairly new to C# (as is probably blantantly obvious.)

Any help, links, suggestions - all are greatly appreciated.

Thanks.

Jasoomian

A: 

you could do this...

private void txtWO_KeyUp(object sender, KeyEventArgs e)    {        
    if (e.KeyCode == Keys.Enter)        {            
         btnFill_Click();
    }    
}
Marcus Pope
Change btnFill_Click() tobtnFill_Click(sender, e);
Marcus Pope
Hey Marcus, thanks for your input. Worked like a charm.
Jasoomian
A: 

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. But it's been my experience that criss-crossing event handlers is very sloppy and leads to maintenance headaches out the wazoo.

Mike Hofer
Nice approach to the issue, Mike. I hadn't thought about the impact of crossing the event handlers. Thanks again.
Jasoomian