开发者

C# executing code from one button in another

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 f开发者_如何学编程rom 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)
    }
}


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.


void EnterPressed(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        button1click(sender, EventArgs.Empty);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜