Calling code of Button from another one in C#

2019-08-14 04:48发布

问题:

I need to know if it's possible to call the Click of a button from another one.

private void myAction_Click(object sender, EventArgs e)
{
    // int x;
    // ...
}

private void Go_Click(object sender, EventArgs e)
{
    // call the myAction_Click button
}

Thanks.

回答1:

You want:

private void Go_Click(object sender, EventArgs e)
{
    myAction_Click(sender, e);
}

But a better design is to pull the code out:

private void myAction_Click(object sender, EventArgs e)
{
    DoSomething();
}

private void Go_Click(object sender, EventArgs e)
{
    DoSomething();
}

private void DoSomething()
{
    // Your code here
}


回答2:

The button has a PerformClick method.

http://msdn.microsoft.com/en-us/library/hkkb40tf(v=vs.90).aspx