Carrick Carrick - 11 months ago 54
C# Question

How to remove all event handlers from a control

To create a new event handler on a control you can do this

c.Click += new EventHandler(mainFormButton_Click);

or this

c.Click += mainFormButton_Click;

and to remove an event handler you can do this

c.Click -= mainFormButton_Click;

But how do you remove all event handlers from a control?

xsl xsl
Answer Source

I found a solution on the MSDN forums. The sample code below will remove all Click events from button1.

public partial class Form1 : Form
        public Form1()

            button1.Click += button1_Click;
            button1.Click += button1_Click2;
            button2.Click += button2_Click;

        private void button1_Click(object sender, EventArgs e)

        private void button1_Click2(object sender, EventArgs e)

        private void button2_Click(object sender, EventArgs e)

        private void RemoveClickEvent(Button b)
            FieldInfo f1 = typeof(Control).GetField("EventClick", 
                BindingFlags.Static | BindingFlags.NonPublic);
            object obj = f1.GetValue(b);
            PropertyInfo pi = b.GetType().GetProperty("Events",  
                BindingFlags.NonPublic | BindingFlags.Instance);
            EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
            list.RemoveHandler(obj, list[obj]);