Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call an event method in C#?

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.

like image 297
Moon Avatar asked Jan 28 '10 05:01

Moon


People also ask

How do you call an event handler method?

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.

How do you call an event on Button?

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.

How do you call an event handler in C#?

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.


2 Answers

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.

like image 87
Juliet Avatar answered Sep 30 '22 03:09

Juliet


// 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);
}
like image 38
SwDevMan81 Avatar answered Sep 30 '22 02:09

SwDevMan81