Remove a dynamically added event handler - c#

I have a code like:
button1.Click += (s, e) =>
{
};
Now how is it possible to remove this handler dynamically? something like:
button1.Click = null;

The point with events is that they are subscribe/unsubscribe, it is not the intention that you should unsubscribe other events then your own. Therefore you need to keep track of your event:
var click = (s, e) =>
{
};
button1.Click += click;
You can then unsubscribe it by:
button1.Click -= click;
EDIT
Seems you can use the approach suggested here.

Related

Is += delegate {} the correct way to attach custom eventargs to a UI control event?

I have been tinkering with Events to gain a better understanding of their use in very general situations. I'm surprised to find the following, so I'm probably heading in the wrong direction...the essence of what I'm doing is changing a button to a random color when it is clicked:
Windows Form
public Form1()
{
ColorChanges KK = new ColorChanges();
KK.ColorEventHandler += handle_ColorChanges;
button1.Click += delegate { KK.ChangeColor(button1); };
}
Event Class
class ColorChanges
{
*... properties & constructor*
public void ChangeColor(object sender)
{
*... randomly assign color to ColorEventArgs*
}
protected virtual void onColorEvent(object sender, ColorEventArgs e)
{
EventHandler<ColorEventArgs> ceh = ColorEventHandler;
{
if (ceh != null)
{
ceh(sender, e)
}
}
}
public event EventHandler<ColorEventArgs> ColorEventHandler;
}
Custom Event Args
public class ColorEventArgs : EventArgs
{
public Color xColor { get; set; }
}
Event Handler
public void handle_ColorChanges(object sender, ColorEventArgs e)
{
if (sender is Button)
{
var ButtonSender = (Button)sender;
ButtonSender.BackColor = e.xColor;
}
}
So the edited questions are:
Is use of the EventHandler(TEventArgs) Delegate useful? MS documentation indicates that syntax like
button1.Click += new EventHandler<AutoRndColorEventArgs>(handle_ColorChanges);
is correct, but that will not reach my code to randomly select a color and an error
"No overload for 'handle_ColorChanges' matches delegate >'System.EventHandler' "
so something like
button1.Click += new EventHandler<AutoRndColorEventArgs>(KK.ChangeColor(button1));
or
button1.Click += new EventHandler(KK.ChangeColor(button1));
Error says that a method is required and if I use
"No overload for 'handle_ColorChanges' matches delegate
'System.EventHandler'"
Lambda expressions help thanks for the supporting answers
button1.Click += (sender,args) => KK.ChangeColor(s);
But that doesn't allow un-assignment and that will be required later...
An anonymous delegate has the same problem
button1.Click += delegate(object sender, EventArgs e)
{ KK.ChangeColor(sender); };
The crux of the problem is that my color methods or their delegates do not match the button delegate signature (object, event). I don't care about the button args and want to use my own HOW?
Is the use of the delegate correct?
Yep, what you are doing is assigning an anonymous delegate as your event handler. This is perfectly valid, however, the catch here is you can't unassign the event handler because you have no reference to it. You could keep a reference to it and do it that way (if required)
var clickHandler = delegate { ... };
button1.Click += clickHandler;
...
button1.Click -= clickHandler
If you need access to the parameters of the event handler you will need to add those into the signature e.g.
button1.Click += delegate (object sender, EventArgs args) { ... }
The new EventHandler(SomeHandlerMethod) construct is the long way of doing things, it's synonymous to += SomeHandlerMethod. Your code currently doesn't work because you are trying to actually call the handler inside the constructor when the constructor expects a reference to the method
+= new EventHandler<ColorEventArgs>(KK.ChangeColor);
Is there a better structure for this?
Yeah, you can do it using even less code
button1.Click += (s, args) => KK.ChangeColor(button1);
This is incorrect:
button1.Click += new EventHandler<AutoRndColorEventArgs>(KK.ChangeColor(button1));
Instead of KK.ChangeColor(button1), you just need to specify the event handler method name as you did in here:
KK.ColorEventHandler += handle_ColorChanges;
The event handler method signature should match with the EventHandler delegate.If you want to just call a method in event handler, you can use lambda statement like this:
button1.Click += (s,e) => KK.ChangeColor(s);
Or:
button1.Click += delegate(object s, EventArgs e) { KK.ChangeColor(s); };
By doing this you are creating an anonymous method and attach it to your Click event.

disable event handler in c# on textchanged

I want to be able to disable or enable textchanged event when I need to.
I have made my function, but I need to dismiss event handler, how can I do that?
Here is my code:
private void textBox1_TextChanged(object sender, EventArgs e)
{
//something
}
This to add the event
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
this to remove the event
textBox1.TextChanged -= new TextChangedEventHandler(textBox1_TextChanged);
Or just the method name
This to add the event
textBox1.TextChanged += textBox1_TextChanged;
this to remove the event
textBox1.TextChanged -= textBox1_TextChanged;
Hope it helps.
simply un-register the event
yourEvent-= YourFunction
and if you want to register again
yourEvent+= YourFunction
You can unsubscribe textchange event. Put following line of code at you want.
textBox1.TextChanged -= textBox1_TextChanged;

How can I unset the following eventhandler?

I've set an eventhandler to an event like this:
frm.FormClosed += (sender, args) =>
{
if (this.myGrid.Enabled)
{
this.myGrid.Select();
}
};
frm.Show();
I want to hang out the eventhandler after the form was closed.
Can you help me?
I want to hang out the eventhandler after the form was closed.
I assume you want to remove it.
Not necessary, don't waste time on it. When the Form is closed (and Disposed), the eventhandler will be collected too. It is a member of the same Form, that follows from the word this in the code.
If you still want to remove it, you will need a copy:
FormClosedEventhandler closeHandler; // class member
closeHandler = (sender, args) =>
{
if (this.myGrid.Enabled)
{
this.myGrid.Select();
}
};
frm.FormClosed += closeHandler ; // OnLoad
...
frm.FormClosed -= closeHandler ; // OnClose
If you mean how to remove you event handler from the event, then you won't be able to use an anonymous delegate but you can create a method with the same parameters and same code and then:
private void EventHandler(object sender, FormClosedEventArgs e)
{
if (this.myGrid.Enabled)
{
this.myGrid.Select();
}
}
frm.FormClosed += EventHandler; // Attach the event handler
frm.FormClosed -= EventHandler; // Remove the event handler

ModalPopUpExtender Button EventHandler Not Firing

I have an eventhandler attached to a button in a modalpopup window. I am trying to pass parameters in the eventhandler but have not had any success. I have tried both lines of code separately and nothing happens when the button is clicked. Is there any other way to pass multiple data from a modalpopup to a method? I've also tried an EventHandler that called a simple method that does not pass any extra parameters and still got nothing.
Thanks
save.Click += (object sndr, EventArgs ee) => saveIssueModal(sndr, ee, cguid, ddlStatus.SelectedValue.ToString());
or
save.Click += delegate(object sender2, EventArgs ee) { saveIssueModal(sender2, ee, cguid, ddlStatus.SelectedValue.ToString()); };
...
Button save = new Button();
save.Text = "Save";
save.Click += new EventHandler(saveIssueModal);
...
issuePnl.Controls.Add(save);
...
IssuesPanel.Controls.Add(issuePnl);
...
issueMPE = new AjaxControlToolkit.ModalPopupExtender();
issueMPE.ID = "issueMPE1";
issueMPE.TargetControlID = newBtn.ID;
issueMPE.PopupControlID = issuePnl.ID;
IssuesPanel.Controls.Add(issueMPE);
Try this:
save.Click += (sender, args) => saveIssueModal(<Custom Arguments>, args);
EDIT:
Try this for assigning a basic event handler:
save.Click += new EventHandler(saveIssueModal);

C# attach event handling with additional parameters

PREFACE
I have a Windows form Button that exposes the event OnClick (object sender, EventArgs e).
In my application I can handle this by using the classic event handling technique of C#:
// Button Creation
Button button = new Button();
button.Click += MyEventHandler;
Then Windows Form ask me for an handler with the following signature:
public void MyEventHandler(object sender, EventArgs e) { }
Suppose that I would like to use lambda expression to do this I can use the syntax:
button.Click += (sender, args) =>
{
// execute the code
};
The drawback of this is that I can't unsubscribe from a Lambda expression.
QUESTION
What I would like to do is to have an utility class that will allow me to handle any Click event plus using an additional Action as a parameter. So I would like to write something like this:
button.Click += MyUtility.Click(()
=> {
// the custom code the Click event will execute
})
Can I do it in somehow?
You can assign the lambda expression to a local variable or field.
For example:
EventHandler handler = (sender, args) =>
{
// execute the code
};
button.Click += handler;
button.Click -= handler;
If you want to unsubscribe inside the handler, you'll need to assign handler to null, then to the lambda, to avoid definite assignment issues.

Categories

Resources