开发者

Manual triggering of events c#

开发者 https://www.devze.com 2023-03-14 09:16 出处:网络
I have a button that when clicked displays some information, can i manually trigger the button clicked event in code ?

I have a button that when clicked displays some information, can i manually trigger the button clicked event in code ?

I need this so that when i click on some other button it a开发者_JS百科utomatically triggers this event too.


A good way would be to have NO code (except a method/function call) in an event handler. this would made it possible to call it from any place in your program.


If you don't care about the sender or EventArgs, you could also simply use

Button1_Click(null, new EventArgs());


Move the code replying to the button click in a function and call that function both in the event handler and in the other.


You can use Button.PerformClick()


You can do it like this.

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("button1");
}

private void button2_Click(object sender, EventArgs e)
{
    MessageBox.Show("button2");
    button1_Click(sender, e);
}


There are two ways to do this,

1# -= Move the code which you have written in the button click event to another function and call this function in this button click event and in other button click event also.

2# - For the second button click event specify the first button click event as the event handler.

3# - call button1's event handler inside button2.

private void button2_Click(object sender, EventArgs e)
{
    button1_Click(sender, e);
}

I will advise you to go for the the second one, if you have to the same set of functionalities for both the buttons.

0

精彩评论

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