How to call an event method in C #?

When I create buttons in C #, does it create a private void button? _click (object sender, EventArgs e).

How do I call the button1_click method from button2_click? Is it possible?

I work with window forms.

+4
source share
5 answers
// No "sender" or event args public void button2_click(object sender, EventArgs e) { button1_click(null, null); } 

or

 // Button2 the sender and event args public void button2_click(object sender, EventArgs e) { button1_click(sender, e); } 

or, as Joel pointed out,

 // Button1 the sender and Button2 event args public void button2_click(object sender, EventArgs e) { button1_click(this.button1, e); } 
+10
source

How to call the button1_click method from button2_click? Is it possible?

It can be fully triggered by a button click event, but this is bad practice. Move the code from your button to a separate method. For instance:

 protected void btnDelete_OnClick(object sender, EventArgs e) { DeleteItem(); } private void DeleteItem() { // your code here } 

This strategy makes it easy for you to directly access your code without the need for any event handlers. In addition, if you need to pull the code from your code behind and into a separate class or DLL, you are two steps ahead of you.

+11
source

You did not mention whether it is Windows Forms, ASP.NET or WPF. If it's Windows Forms, another suggestion is to use button2. PerformClick (). I find this to be cleaner since you are not directly calling the event handler.

+3
source

You can hook up button events in the ASPX file code.

The button tag will project the following events:

 <asp:Button Text="Button1" OnClick="Event_handler_name1" /> <asp:Button Text="Button2" OnClick="Event_handler_name1" /> 

Just connect OnClick = to your handler method for button 1

+2
source

You can bind the same handler for the event of both buttons

+2
source

Source: https://habr.com/ru/post/1299620/


All Articles