0

I've one button - button1click and textbox in which when i type something and press enter, i'd like to run code from button1click.

How can I do it without copying entire code from button1click into EnterPressed?

private void button1click(object sender, EventArgs e)
{
    //Some Code
}


void EnterPressed(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        Execute code from button1
    }
}

Maybe something like that? But I'm getting errors...

void EnterPressed(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        button1click(object sender, EventArgs e)
    }
}
1
  • wondering ,setting the AcceptButton property of the form would have resulted in the same behaviour. Commented Apr 11, 2011 at 8:11

2 Answers 2

6

Just have button1_click call a method and then you can call that same method from anywhere you want to. So in your example:

private void button1click(object sender, EventArgs e)
{
       Foo();
}


void EnterPressed(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        Foo();
    }
}

void Foo()
{
    //Do Something
}

I personally wouldn't manually call another control's event.

Sign up to request clarification or add additional context in comments.

3 Comments

Your last line is too much FUD, there's nothing wrong with doing this.
Tnx :) You're right with this calling another contro's event.
@Hans, personal preference I guess. For readability purposes, I prefer to actually call a method rather than a button click event in cases such as this.
1
void EnterPressed(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        button1click(sender, EventArgs.Empty);
    }
}

1 Comment

@abatishchev: I don't know what was wrong, but thanks for making it correct :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.