Every Control in C# is full of events like MouseButtonDown and KeyDown, but what happens when you want an object to fire an event that isn't already built in? This snippet tutorial will go through all the code required to create your own events and custom event handlers.
As an example, I'm going to create a class that holds information about a car. This will include make, model, year, and owner. When information about the car is changed, this class will fire events letting anyone who is listening know that something has changed.
Below is the basic class with all the members mentioned above. I've also added properties to get and set each variable.
using System;
namespace CustomEvents
{
public class Car
{
private string make;
private string model;
private int year;
private string owner;
public string CarMake
{
get { return this.make; }
set { this.make = value; }
}
public string CarModel
{
get { return this.model; }
set { this.model = value; }
}
public int CarYear
{
get { return this.year; }
set { this.year = value; }
}
public string CarOwner
{
get { return this.owner; }
set { this.owner = value; }
}
public Car()
{
}
}
}
Let's say I want to know whenever the Owner property of my Car object
changes. The quickest way to do this is to use simply use an event
handler delegate already supplied by Microsoft - such as EventHandler.
using System;
namespace CustomEvents
{
public class Car
{
public event EventHandler OwnerChanged;
private string make;
private string model;
private int year;
private string owner;
public string CarMake
{
get { return this.make; }
set { this.make = value; }
}
public string CarModel
{
get { return this.model; }
set { this.model = value; }
}
public int CarYear
{
get { return this.year; }
set { this.year = value; }
}
public string CarOwner
{
get { return this.owner; }
set
{
this.owner = value;
if (this.OwnerChanged != null)
this.OwnerChanged(this, new EventArgs());
}
}
public Car()
{
}
}
}
Here I created an event which uses the EventHandler delegate and
called it OwnerChanged. I fire the event in the CarOwner property
whenever it is set. When firing the event, you should always check to
make sure it's not null. The event will be null if no one is listening
for it - you can't fire an event to no one. Once you determined the
event is not null, you simply execute it like any other method. The
EventHandler signature requires an object and EventArgs as
parameters, so I pass in this and a new instance of the EventArgs
class. Now let's see how use this event.
Car car = new Car();
//adds an event handler to the OwnerChanged event
car.OwnerChanged += new EventHandler(car_OwnerChanged);
//setting this will fire the OwnerChanged event
car.CarOwner = "The Reddest";
This code simply creates a car object, attaches to the OwnerChanged
event, and sets the CarOwner property. As you can see, using custom
events is exactly the same as using built in events. In the code above,
whenever the CarOwner property is set, the function car_OwnerChanged
will be called.
void car_OwnerChanged(object sender, EventArgs e)
{
//the CarOwner property has been modified
}
Now let's say I want the new owner passed in through the event. I could
do this with the current event handler by passing the car's owner as
sender, but that would mean I have to cast it whenever the event is
fired. I also have this EventArgs parameter that I'm not using
anywhere.
public string CarOwner
{
get { return this.owner; }
set
{
this.owner = value;
if (this.OwnerChanged != null)
this.OwnerChanged(value, new EventArgs());
}
}
Here's a modified version of the CarOwner property that passes the new
name through the event. The problem here is that value is passed
through as an object, so on the receiving end, they would have to cast
it back to a string to get the car's new owner. What we want is a new
event handler delegate that doesn't need those parameters. To do this
we'll first have to declare a new delegate matching the method signature
we want and then create an event using the new delegate.
using System;
namespace CustomEvents
{
public class Car
{
public delegate void OwnerChangedEventHandler(string newOwner);
public event OwnerChangedEventHandler OwnerChanged;
private string make;
private string model;
private int year;
private string owner;
public string CarMake
{
get { return this.make; }
set { this.make = value; }
}
public string CarModel
{
get { return this.model; }
set { this.model = value; }
}
public int CarYear
{
get { return this.year; }
set { this.year = value; }
}
public string CarOwner
{
get { return this.owner; }
set
{
this.owner = value;
if (this.OwnerChanged != null)
this.OwnerChanged(value);
}
}
public Car()
{
}
}
}
Here we create a delegate that takes a string as an argument. We then create an event handler using our new delegate. Lastly I modified the CarOwner property to use our new event handler. The code required to listen for our new event handler is identical to before except for the new delegate.
Car car = new Car();
//adds an event handler to the OwnerChanged event
car.OwnerChanged += new OwnerChangedEventHandler(car_OwnerChanged);
//setting this will fire the OwnerChanged event
car.CarOwner = "The Reddest";
Now whenever car_OwnerChanged is called, the car's owner is passed in
as a string. That's all the code required to create and use your own
custom events and event handlers.
Very nice and simple, good stuff
This is a nice example of how to generate an event, but I'd like to find a nice example of how the event can be useful.
Thanks man! This is exactly the thing I was looking for...
Very nice, a simple code with works
Very nice, this is just what i needed to get around the limitations of multi-threading!
before i knew how to get around those limitations with events like this. i would create a string that would hold the info thats changed from the non-graphics thread and have a timer run on the main thread and have it periodicly check the updated info.
good tutorial and example on how to create new event.
Really very nice and simple.My confusion abt events and delegates cleared now.Good Service. Thank you very much
Extremely useful. Thanks a lot
Very clear and useful. Cleared up events for me perfectly.
Gosh! I've been looking for something simple out there that can make me understand the creation of these events.
Great tutorial! You're a life saver!
What I was looking for exactly. Simple and useful. Thank you.
Thanks for a VERY clear and VERY helpful tutorial. Awesome! I have saved this in my bookmarks of very helpful webpages.
Finally found what i have bbeen looking for , for ages. never found anything as simple and straighforward as this - so beautifully explaining events and basic delagates.
Thanks for taking the time to write this up. Nice job on showing how the code works by modifying the same code over and over till you get to the end. This topic is too complex to show one big snippet of code and try to explain it all. The car idea made for a good tutorial as well. Better than the New News example I was trying to follow.
I confirm, such explanation is rare. You don't go directly to the final solution but explain the reason of each element separately step-by-step.
Great Job. thanks
nice
excellent mate. very good for new learner.
Thank you, I appreciate the simplicity!
Excellent, just what I needed. Thanks!
Thanks. It's worth to say that your effort was so great. Thanks a lot. Looking forward your new posts.
I still have a bit of problem understanding this fully. I get what you are telling but let's say I want to set one of the other fields when the OwnerChanged event is fired. Maybe I need to set a different licenseplate when the owner has changed.
How would I do that?
You'd probably want to add the sender to the custom event handler in that case.
Then change the desired property on the event:
Excellent!!!! Thank you.
Thanks, this was extremely clear and well presented.
what am I doing wrong I get this error (I copied and paste as it was in the article)
Error 1 The type or namespace name 'OwnerChangedEventHandler' could not be found (are you missing a using directive or an assembly reference?)
please help
it is fixed now I got to change the code like this ( need it to add "Car." as I was calling it from another class
car.OwnerChanged += new Car.OwnerChangedEventHandler(car_OwnerChanged);
thank you for this clean explanation, I been looking for days for a simple explanation that I could understand, afer following some 5 tutorials, this is the one that did.
This is the best explanation of custom event handlers I've ever seen. Thanks
Thanks. This is a nice explanation that helped me to understand about events.
Good work!
Beautiful example... thanks a lot..
Your tutorials are so easy to understand. Thanks
I must say this is the best tutorial on event handling I’ve seen, great!
I just love your tutorials. Very clear and concise :) Thanks again!
I have existing code that follows your tutorial. The issue I have is that the event has mutiple handlers and only one is being fired. I have stepped through the code and I add about 30 odd handlers for this event. But only one is fired.
Can you give me some ideas to look for in my code.
I am wary of events in .net, as you have rightly stated the complexities involved, in another of your article on events. I am afraid of using them, hence forget all about them, and everytime I come across a reading on delegate and events - I sit up with curiosity - as though I am reading for the first time:) To make things worse, they differ so much across C# and vb.net. Nice article, thanks!
This bit of code here:
Looks like it's making sure that the .OwnerChanged event is being "listened to" or wired-up. Correct?
Yes. If anything is attached to the event, it won't be null. If the event is raised without anything attached, you'll receive a null reference exception. Checking for null is much more efficient than putting the event raise inside a try-catch block.
Hi
I copied the example but I have one problem with the Line: if(this.OwnerChanged != null) ==> it blocks me Since "this.OwnerChanged" is always null and complains of "missing Object Reference" I see that : "car.OwnerChanged += new ... " is ignored , if not declared inside Class Car but is in different class (like Form1.cs)
What should I do to make it work from : Form1.cs ? AVR
To solve it : needs to declare a static event handler "Public static event OwnerchangedEventhandler..." and it require now to call class members by the name of the Class ==> "Car" instead of "car"
public partial class MyUserControl : System.Web.UI.UserControl { public delegate void Handler1(object sender, EventArgs e); public static event Handler1 CountrySelectedIndexChange; public static event Handler1 StateSelectedIndexChange; public static event Handler1 btnUploadClick; public static event Handler1 btnSubmitClick; public static event Handler1 btnCancelClick; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { clsCountry_Master objCountry = new clsCountry_Master(); DataTable dtCounry = objCountry.GetAllCountry_Master(); objCountry.FillFilteredRADComboList(rcbCountryName, dtCounry); } } protected virtual void rcbCountryName_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e) {
string CounryName = rcbCountryName.Text; if (rcbCountryName.Text != null) { CountrySelectedIndexChange(this, e); } } protected void rcbStateName_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e) { if (StateSelectedIndexChange != null) { StateSelectedIndexChange(this,e); } } protected void btnUpload_Click(object sender, EventArgs e) { if (btnUploadClick != null) { btnUploadClick(this, e); } } protected void btnSubmit_Click(object sender, EventArgs e) { if (btnSubmitClick != null) { btnSubmitClick(this, e); } } protected void btnCancel_Click(object sender, EventArgs e) { if (btnCancelClick != null) { btnCancelClick(this, e); } } public string SelectedCountryValue { get { return rcbCountryName.SelectedValue; } set { rcbCountryName.SelectedValue = value; } } } public class EventHandler1EventArgs : EventArgs { private int _reached; public EventHandler1EventArgs(int num) { this._reached = num; } public int ReachedNumber { get { return _reached; } } } ***************** this is my ascx.cs file.I am getting NULL Value for every event. So please help me.
Many thanks the real-world example explains the concept brilliantly.
Very very clear explanation. Thank you :)
?????? ?? ?????????
sender.LicencePlate = "Isting 09/29/2009 - 10:28 ?????? ?? ?????????
sender.LicensePlate = "? ??? ???? ?????? ????????"
Hi!
I've concatenated your tutorials' examples about serialization and this one to make datagrid viewable class that can be serialized. But there's a problem. I don't know how to perform it mostly because of
field. And there's one more question. When DataGrid is edited, we have our BindingList updated, right? But can I add some other functions that are need to be performed when something's changed in BindingList? Thank you very much in advance.
Actually,
I debugged this code and I can say that BindingList (precedents) changes okay, but datagrid still shows things that was before this method was called.
Good Article...Thanks
This is the best explanation on the
topic I have seen so far! Thank you!
Wow! Best of all!
Nice simple and easy to understand article Thanks man..
wonderful article . simply explained :)
thank you so much for this clean explanation on events. It makes sense to me now.
I have small problem.
I made 4 textboxes (make, model,year and owner) and a button.
When I change a owner, event fires up correctly, however it keeps repeating it's self.
For example, I have this code:
When I change the owner, message box pops. When I change it again, message box pops 2 times (must ok it). If I do it 10 times, there will be 10 text boxes.
How do I make it pop only once?
Are you attaching the event more than once? Can you paste the code where the event handler is being attached?
Thank you for fast reply :)
Here is my class code:
And here is form code.
What's happening is every time you click the button you attach the event again. Your handler will be called for every hook that you make. You should take this line:
and move it into the constructor, or somewhere else so it's only called once.
And again thank you so much.
I would like to thank you for your time maintaining this web site. For dedicating your free time to help us, with these tutorials that are best on the web.
Every single text here, is understandable and easy to follow. Have you thought about publishing a book?
I know that this is my first web site to check every morning.
Keep on doing great things, and as soon as I have something to publish, I will do it here :)
Great Article! Helped me a lot.
i learnt lot from this site thank u all..........
Nice explanation. Keep posting such articles.
so... an event is just a C function pointer with microsoft naming parafernalia.
Great article! Precisely written! Thank you!
I have been learning events and I am not sure why i should use events in my code, it seems events are only usefull in an object which will be reused by a third party i.e thats why microsoft have so many events in there objects because they will be used by third parties and do not know hgow those third parties want to use the object so events is a good way of giving a choice, but in code that will not be reused, i dont see any reason for using events over just a method, i.e your car example, if i know that every car will have an owner change, why put in an event over a method, if is just different types of car then why not put a method at base level, so events seem a bit off overkill if you are creating code for yourself. Is this correct.
Finally, the lesson on custom events that I have been looking for. I have never understood WHY the delegate was used before reading this and now I get it. Thanks a million!
man, this has been very helpful. thank you for the clear explanation
thanks. very nice and to the point
Great example. Simple and clean.
Surprising how long it takes other people to explain the concept of C# events! I spent a half hour surfing before I found your example and then "got it" in minutes. Thanks!
Very Nice!!!
Nice one! That's exactly what i was looking for!:) thanks
will it be posible to explain why the event handler is static in this http://msdn.microsoft.com/en-us/library/w9y9a401(v=VS.100).aspx example ?
i tryed removing the static and it does not run, even tho neither the compiler nor the CLR complains
TIA
Simple example to show custom event and event handling using System; class myarray { public int[] num=new int[5]; public delegate void sortHandler(int[] ab); //delegate defined public event sortHandler sort; //event sort is defined based on delegate sortHandler public myarray() { int i; this.sort+=new sortHandler(num_sort); //sort event is added to this class for(i=0;i
Your examples and presentation seen ALWAYS to be the clearest of all I check. Thank-you for your time and efforts!!
Nice but I don't knew About Delegates..........
nice and clean explanation
Thanks for the tutorial. Nice clear language which helped me understand it on the first read.
Another happy coder here. This is the only damn tutorial out there that could teach me event handling. Not even MSDN had a good explanation. THANK YOU!
This is best tutorial for custom event handling. Thanks..!!!!!!
Thank you!
Is Safe Thread?
public string CarOwner { get { return this.owner; } set { this.owner = value; if (this.OwnerChanged != null) // q1 this.OwnerChanged(this, new EventArgs());// q2 } }
1thread 2thread current line -> q1
1Thread q1 -> change OwnerChanged = null and.. 2Thread q2 excute...
2thread null Ownerchanged excute...
is safe thread?
You are right, that is not thread safe.
Car car = new Car();
//adds an event handler to the OwnerChanged event car.OwnerChanged += new OwnerChangedEventHandler(car_OwnerChanged);
//setting this will fire the OwnerChanged event car.CarOwner = "The Reddest";
...I have some problem in this line...
car.OwnerChanged += new Car.OwnerChangedEventHandler(car_OwnerChanged);
why it use Car ..class name instead of using our created instance car....
I dun understand.. In my opinion..It should be car.OwnerChangedEventHandler(car_OwnerChanged);
please help in this confussion
This is a great article which I ever found.Thank you very much.
thank you very much for this fruitful example.
You are like angel after some hours of nothing :)
thx
keep on the good work, GOD bless u my frnd !!
Thanx, This was a very clear and instructional
Hey, Custom events well explained. Just wanted to clarify one thing. What you have done is whenever a property is changed or set, we just want to call a method. Why cant we just do a method call directly from the property's set, without having to use events? Is there something i'm missing here?
Never worked on a real usage of custom events. It would be great if you can list a few of custom events in real time projects.
Thanks
The best reason to use events is to eliminate unneeded dependencies. If we were to use a direct method call, then the Car class would have a dependency on another object - the one that defines the method.
If we wanted to use the Car class is several different projects and by several different consumers, the Car class doesn't need to know anything about them. All it has to do is fire an event - any object can then attach and be notified.
Most objects in the .NET framework are implemented this way. The Button class has a Click event. This allows the Button class to be used in a million different projects by a million different developers.
Thank you. I was reading a convoluted example in a text book, which had me scratching my head. One read through your tutorial was all that was required and no head scratching :-) Very clear. Thanks again.
Hello for some reason this line of code is cannot be recognised by my IDE. Could you please help
car.OwnerChanged += new OwnerChangedEventHandler(OwnerChangedHandler);
Error message= Error 1 The type or namespace name 'OwnerChangedEventHandler' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Pawan\AppData\Local\Temporary Projects\WindowsFormsApplication1\Form1.cs 19 37 WindowsFormsApplication1
Here's the full Code
Really helpful.....
Thanks a lot for this useful article.
public partial class MyUserControl : System.Web.UI.UserControl { public delegate void Handler1(object sender, EventArgs e); public static event Handler1 CountrySelectedIndexChange; public static event Handler1 StateSelectedIndexChange; public static event Handler1 btnUploadClick; public static event Handler1 btnSubmitClick; public static event Handler1 btnCancelClick; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { clsCountry_Master objCountry = new clsCountry_Master(); DataTable dtCounry = objCountry.GetAllCountry_Master(); objCountry.FillFilteredRADComboList(rcbCountryName, dtCounry); } } protected virtual void rcbCountryName_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e) {
string CounryName = rcbCountryName.Text; if (rcbCountryName.Text != null) { CountrySelectedIndexChange(this, e); } } protected void rcbStateName_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e) { if (StateSelectedIndexChange != null) { StateSelectedIndexChange(this,e); } } protected void btnUpload_Click(object sender, EventArgs e) { if (btnUploadClick != null) { btnUploadClick(this, e); } } protected void btnSubmit_Click(object sender, EventArgs e) { if (btnSubmitClick != null) { btnSubmitClick(this, e); } } protected void btnCancel_Click(object sender, EventArgs e) { if (btnCancelClick != null) { btnCancelClick(this, e); } }
public string SelectedCountryValue { get { return rcbCountryName.SelectedValue; } set { rcbCountryName.SelectedValue = value; } } } ***************** this is my ascx.cs file.I am getting NULL Value for every event. So please help me.
PLEASE SEND YOUR ANSWERS TO cbgbala@gmail.com
Please Help Me............
I registered an account just to comment this is the best explanation of custom events I have ever read. You should write a book. Thanks so much!
-d