The first one code is shorthand notation of second:
itemCountLines.Click = itemCountLines.Click + (sender, args) => countLines();
itemCountLines.Click += (sender, args) => CountLines();
But i did not understand what this expression is doing.Anybody Please Explain it to me
This code adds an handler to the Control.Click event:
public event EventHandler Click
where EventHandler is a delegate of type:
public delegate void EventHandler(
object sender,
EventArgs e
)
Normally, given you have a method with the same signature:
void SomeClickHandler(object sender, EventArgs e)
{
CountLines();
}
you would add this handler to handle Click event:
itemCountLines.Click += SomeClickHandler;
Operator += is possible because Click is an event, so you can add or remove a multiple EventHandlers to it. Simple speaking, after some control is clicked, you may want to make multiple actions (show some other control, log it to the database etc) so you are able to add multiple event handlers. You can even do itemCountLines.Click -= SomeClickHandler somewhere later to say, you do not want to handle Click with SomeClickHandler anymore.
But above code needs to define method SomeClickHandler which sometimes is unnecessary (for example, it is used only one in whole class). Then you can use anonymous delegate (added in C# 2.0):
itemCountLines.Click += delegate(object sender, EventArgs args)
{
CountLines();
};
but you can further shorten this syntax with lambda expression (added in C# 3.0) to:
itemCountLines.Click += (sender, args) => CountLines();
It simply add an event to the list of listeners itemCountLines.Click = itemCountLines.Click + (sender, args) so when an event occurs the instance of sender will be notified to raise the event inline => countLines(); as you are using lambda Expression => which will invoke countLines method
You're just attaching an event on Click, it is the same as saying
itemCountLines.Click += CountLines(sender, args);
Somewhere, there should be a method like this :
private void CountLines()
{
// Some Code There
}
Related
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.
I'm constructing a Form and it has several numericUpDown controls, several checkbox controls and some text boxes etc. Each control has a event method (CheckedChanged, ValueChanged etc) that is triggered that does something but my main quesiton is this:
What I want to do is run a single method which will update a text field on my form but currently I have it just repeated 24 times. This works but I feel there must be a better way ... Below is an example of what I have so far.
private void button3_Click(object sender, EventArgs e)
{
// Code Specific to the Buton3_Click
UpdateTextLabel();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
// Code Specific to the checkBox1_CheckChanged
UpdateTextLabel();
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
// numericUpDown1 specific code ....
UpdateTextLabel();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// comboBox1 specific stuff ...
UpdateTextLabel();
}
// .... and so on for every method ....
Is there a better way to achieve this? I want to say "if any control is clicked or changed ... DO THIS "UpdateTextLabel()" thing " but not sure how to go about it. Happy to be directed to the answer as the questions I typed into search didn't seem to be the "right questions" ...
Thanks!
yes, any events of any controls can share the same event handler method as long as their event handler delegates are the same, in this case, the event handler delegates of those controls are all of type "EventHandler" (no return value and 2 arguments: object sender and EventArgs e).
private void UpdateTextLabel(object sender, EventArgs e)
{
//your original UpdateTextLabel code here
}
button3.Click += UpdateTextLabel;
checkBox1.CheckedChanged += UpdateTextLabel;
numericUpDown1.ValueChanged += UpdateTextLabel;
comboBox1.SelectedIndexChanged += UpdateTextLabel;
For sure! You can use lambdas to easily deal with the unused arguments:
button3.Click += (sender, args) => UpdateTextLabel();
checkBox1.CheckedChanged += (sender, args) => UpdateTextLabel();
numericUpDown1.ValueChanged += (sender, args) => UpdateTextLabel();
comboBox1.SelectedIndexChanged += (sender, args) => UpdateTextLabel();
Or as some developers are trending, if you don't care about the args, you can use underscores to "ignore" them for readability:
button3.Click += (_, __) => UpdateTextLabel();
checkBox1.CheckedChanged += (_, __) => UpdateTextLabel();
numericUpDown1.ValueChanged += (_, __) => UpdateTextLabel();
comboBox1.SelectedIndexChanged += (_, __) => UpdateTextLabel();
As the mighty Jon Skeet once schooled me, this is far superior to the default Visual Studio naming scheme of CONTROLNAME_EVENTNAME as you can easily read "when button 3 is clicked, update the text label", or "when the combobox is changed, update the text label". It also frees up your code file to eliminate a bunch of useless method wrappers. :)
EDIT: If you have it repeated 24 times, that seems a bit odd from a design standpoint. ... reads again Oh darn. I missed the comments, you want to run specific code as well as update the text box. Well, you could register more than one event:
button3.Click += (_, __) => SubmitForm();
button3.Click += (_, __) => UpdateTextLabel();
The problem with this, is technically, event listeners are not guaranteed to fire in-order. However, with this simple case (especially if you don't use -= and combine event handlers) you should be fine to maintain the order of execution. (I'm assuming you require UpdateTextLabel to fire after SubmitForm)
Or you can move the UpdateTextLabel call into your button handler:
button3.Click += (_, __) => SubmitForm();
private void SubmitForm(object sender, EventArgs e)
{
//do submission stuff
UpdateTextLabel();
}
Which kinda puts you into the same boat (albeit with better method naming). Perhaps instead you should move the UpdateTextLabel into a general "rebind" for your form:
button3.Click += (_, __) => SubmitForm();
private void SubmitForm(object sender, EventArgs e)
{
//do submission stuff
Rebind();
}
private void Rebind()
{
GatherInfo();
UpdateTextLabel();
UpdateTitles();
}
This way if you have to do additional work besides just updating a text label, all your code is calling a general Rebind (or whatever you want to call it) and it's easier to update.
EDITx2: I realized, another option is to use Aspect Oriented Programming. With something like PostSharp you can adorn methods to execute special code which gets compiled in. I'm 99% sure PostSharp allows you to attach to events (though I've never done that specifically):
button3.Click += (_, __) => SubmitForm();
[RebindForm]
private void SubmitForm(object sender, EventArgs e)
{
//do submission stuff
}
[Serializable]
public class RebindFormAttribute : OnMethodBoundaryAspect
{
public override void OnSuccess( MethodExecutionArgs args )
{
MyForm form = args.InstanceTarget as MyForm; //I actually forgot the "InstanceTarget" syntax off the top of my head, but something like that is there
if (form != null)
{
form.Rebind();
}
}
}
So even though we do not explicitly make a call anywhere to Rebind(), the attribute and Aspect Oriented Programming ends up running that extra code OnSuccess there whenever the method is invoked successfully.
Yes, you don't want to write code like this. You don't have to, the Application.Idle event is ideal to update UI state. It runs every time after Winforms retrieved all pending messages from the message queue. So is guaranteed to run after any of the events you currently subscribe. Make it look like this:
public Form1() {
InitializeComponent();
Application.Idle += UpdateTextLabel;
this.FormClosed += delegate { Application.Idle -= UpdateTextLabel; };
}
void UpdateTextLabel(object sender, EventArgs e) {
// etc..
}
I wish to programatically unsubscribe to an event, which as been wired up.
I wish to know how I can unsubscribe to the EndRequest event.
I'm not to sure how to do this, considering i'm using inline code. (is that the correct technical term?)
I know i can use the some.Event -= MethodName to unsubscribe .. but I don't have a method name, here.
The reason I'm using the inline code is because I wish to reference a variable defined outside of the event (which I required .. but feels smelly... i feel like I need to pass it in).
Any suggestions?
Code time..
public void Init(HttpApplication httpApplication)
{
httpApplication.EndRequest += (sender, e) =>
{
if (some logic)
HandleCustomErrors(httpApplication, sender, e,
(HttpStatusCode)httpApplication.Response.StatusCode);
};
httpApplication.Error += (sender, e) =>
HandleCustomErrors(httpApplication, sender, e);
}
private static void HandleCustomErrors(HttpApplication httpApplication,
object sender, EventArgs e,
HttpStatusCode httpStatusCode =
HttpStatusCode.InternalServerError)
{ ... }
This is just some sample code I have, for me to handle errors in a ASP.NET application.
NOTE: Please don't turn this into a discussion about ASP.NET error handling. I'm just playing around with events and using these events for some sample R&D / learning.
It's not possible to unsubscribe that anonymous delegate. You would need to store it in a variable and unsubscribe it later:
EndRequestEventHandler handler = (sender, e) =>
{
if (some logic)
HandleCustomErrors(httpApplication, sender, e,
(HttpStatusCode)httpApplication.Response.StatusCode);
};
httpApplication.EndRequest += handler;
// do stuff
httpApplication.EndRequest -= handler;
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
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.