C# - Event Handlers, Part I

Hello everyone!  Today we'll be covering basic control event handlers, I hope you enjoy it. :)

Event List
Each control has its default event handler that is automaticlly created when its double clicked.  The button has its Click() event, the textBox with the TextChanged() event.  Sometimes you want to add an event that also pretains to the control but isnt the defualt event.  The easiet way to do this is click the control of which you want to create an event for and goto it's properties window.  From here you should see a lightining bolt, click this and you should see a large list of events you can create for the control. 

Attached File  events-Tut.png   71.25K   67 downloads
Once you've found the new event you want to create double click it and you'll be directed back to code view with a newly created event function looking something like this:
Attached File  events-Tut-New.png   8.94K   27 downloads

Now you maybe wondering why you cant just save yourself some trouble and just write
private void button1_FontChanged(object sender, EventArgs e)
{
}
Instead of adding it through the events list?  Well you can do this, but this only creates the event function, you would still have to create an event handler in the Designer.cs file.  Since were at it let's go over how to do this.  


Designer.cs & Form1.cs Coded Events.
First open your Designer.cs file and find the control you want to add an event for, then add this.
 this.controlNameHere.EventNameHERE += new System.EventHandler(this.FunctionName);

Here is what mine looks like with the fontChanged event in place.
Attached File  events-Tut-Design.png   117.62K   57 downloads

Don't forget to add this to your form code when your d

one in the designer.

private void FunctionName(object sender, EventArgs e)
{
}

There!  Now you know how to use both ways of creating an event, but there is still one other way that is slighlty easier then the Designer.cs method.  

This method requires you to create a new eventHandler much like we did in the Designer, except this time we add the code in our Form.
controlName.eventName += new EventHandler(funtionName); 

Here's what mine looks like, event function included.
Attached File  events-Tut-Form.png   23.68K   35 downloads


Tip: When adding a new event to a control you will see a lightning bolt next to the event in the auto-complete window.
Attached File  events-Tut-Auto.png   23.17K   36 downloads


Thats the basics of creating event handlers in C#.  If you want to know how to add an event that isnt covered in the event list?  Well that will be covered in Part II.  


No comments:

Post a Comment