When I create buttons in C#, it creates private void button_Click(object sender, EventArgs e)
method as well.
How do I call button1_click
method from button2_click
?
Is it possible?
I am working with Windows Forms.
Call an event handler using AddHandler Make sure the event is declared with an Event statement. Execute an AddHandler statement to dynamically connect the event-handling Sub procedure with the event.
To make click event work add android:onClick attribute to the Button element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.
Event handlers in C# An event handler in C# is a delegate with a special signature, given below. The first parameter (sender) in the above declaration specifies the object that fired the event. The second parameter (e) of the above declaration holds data that can be used in the event handler.
How do I call button1_click method from button2_click? Is it possible?
Its wholly possible to invoke the button's click event, but its a bad practice. Move the code from your button into a separate method. For example:
protected void btnDelete_OnClick(object sender, EventArgs e)
{
DeleteItem();
}
private void DeleteItem()
{
// your code here
}
This strategy makes it easy for you to call your code directly without having to invoke any event handlers. Additionally, if you need to pull your code out of your code behind and into a separate class or DLL, you're already two steps ahead of yourself.
// No "sender" or event args
public void button2_click(object sender, EventArgs e)
{
button1_click(null, null);
}
or
// Button2's the sender and event args
public void button2_click(object sender, EventArgs e)
{
button1_click(sender, e);
}
or as Joel pointed out:
// Button1's the sender and Button2's event args
public void button2_click(object sender, EventArgs e)
{
button1_click(this.button1, e);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With