开发者

How Can I Remove Event?

I am adding a event like开发者_运维知识库 that

Button button = new Button();

button.Click += (o,e) =>
{
//Somecode
};

How can Remove this event?


The correct syntax is

button.Click += (o, e) => {  /*code*/ };

You can't remove that, as it is an anomynous method (a lambda). If you want to be able to remove an event handler, you'll have to move the code to an extra method.

If you save the lambda as a delegate:

EventHandler<EventArgs> handler = (o, e) => {  //code };

You can add/remove it:

button.Click += handler;
button.Click -= handler;

However, I'd strongly advise against that. Use a named method instead.


The short answer: you can't, you can only remove the handler of the event by -=. if you want to remove the handler then don't use anonymous methods. instead use a predefined method like:

button.Click += OnButtonClick;

private void OnButtonClick(object sender, EventArgs e)
{
    //some code
} 


You can do that if you store the delegate.

Button button=new Button();

EventHandler<...> handler=(o,e)=>
{
//Somecode
}

button.Click+=handler;
button.Click-=handler;

But I recommend using a named method instead. I see no gain in using a lambda here.


This may help;

        Button btn = new Button();
        this.Controls.Add(btn);
        btn.Click += (o, x) =>
        {
            Button b = o as Button;
            FieldInfo eventclick = typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
            object eventValue = eventclick.GetValue(b);
            PropertyInfo events = b.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
            EventHandlerList eventHandlerList = (EventHandlerList)events.GetValue(b, null);
            eventHandlerList .RemoveHandler(eventValue, eventHandlerList [eventValue]);
            MessageBox.Show("Test");
        };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜