Add and Delete Event in C#

Shervan360 1,661 Reputation points
2022-07-26T20:14:05.867+00:00

Hello,

I created simple Windows Forms app in C#.
Why is it not possible to remove from the clickMeButton1.Click event?
I expected ClickMeButton1_Click method executed one time because I detach method from event with clickMeButton1.Click -= ClickMeButton1_Click;

The whole project in OneDrive:
https://1drv.ms/u/s!AiKKqJaRZheDognJPo0Ih379wgBQ?e=9qDZVY

224994-screenshot-2022-07-26-160752.png

namespace WinFormsApp1  
{  
    public partial class Form1 : Form  
    {  
        public Form1()  
        {  
            InitializeComponent();  
        }  
  
        private void Form1_Load(object sender, EventArgs e)  
        {  
            clickMeButton1.Click += ClickMeButton1_Click; //execute   
            clickMeButton1.Click += ClickMeButton1_Click; // execute  
            clickMeButton1.Click += ClickMeButton1_Click; // execute  
        }  
  
        private void ClickMeButton1_Click(object? sender, EventArgs e)  
        {  
            MessageBox.Show("Hi!"); //executed 3 times  
            clickMeButton1.Click -= ClickMeButton1_Click;  
            clickMeButton1.Click -= ClickMeButton1_Click;  
            clickMeButton1.Click -= ClickMeButton1_Click;  
            clickMeButton1.Click -= ClickMeButton1_Click;  
            clickMeButton1.Click -= ClickMeButton1_Click;  
            clickMeButton1.Click -= ClickMeButton1_Click;  
            clickMeButton1.Click -= ClickMeButton1_Click;  
            clickMeButton1.Click -= ClickMeButton1_Click;  
            clickMeButton1.Click -= ClickMeButton1_Click;  
            clickMeButton1.Click -= ClickMeButton1_Click;  
            MessageBox.Show("Bye!"); //executed 3 times  
        }  
    }  
}  
Developer technologies Windows Forms
Developer technologies C#
{count} vote

1 answer

Sort by: Most helpful
  1. Reza Aghaei 4,986 Reputation points MVP Volunteer Moderator
    2022-07-26T20:35:34.133+00:00

    It's expected behavior.

    You have assigned the event handler 3 times, right? Then when you click on the button it will run 3 times, no matter what you do inside the event handler.

    So it basically does this for 3 times:

    • Show Hi
    • Remove event handler 10 times
    • Show Bye

    After completing these 3 rounds, now if you click on the button again, it doesn't run the event handler, because you have removed the event handlers. Well, as a side-note, you don't need to remove the event handler 10 times; 1 time will be enough.

    You should not assign the event handler more than once. If you assigned, then you cannot disable it inside the event handler itself, it's too late.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.