Almost exactly two years ago, I published the Passing Data Between Forms post. I have had numerous questions and comments about that post and now I’ve decided that it deserves an additional example.
In that post, I had an example (the 3rd one) that utilized Interfaces. In the example, we had a MainForm that passed a DataSet to Form1. Form1 then allowed the user to make some changes to the data in that DataSet and then we wanted to have MainForm automatically reflect those changes ... even while the user was still working in Form1. An interface worked well for that scenario. At the time, I wanted to keep the post simple so as not to confuse beginners. But, I really need to expand on that example and show how to accomplish this task using delegates/events.
So, without further ado (pun intended), here it is:
First, let's take a look at Form1. Minimally, you can implement this whole thing with a simple event, which uses standard EventArgs, as follows:
Then, the MainForm looks like this:
In this particular case, we don't really need EventArgs. Because we passed the DataSet into Form1 to begin with, we already know everything we need to know, namely the data that has changed will be the same DataSet that we passed into Form1. So, since we don’t need any EventArgs, we could create a custom delegate to use as our event handler. We will change our two forms like this:
The only difference in MainForm is that the event handler doesn't need the usual parameters (object sender, EventArgs e), so change the DataChanged event handler to look like this:
Another way of handling the event in the MainForm is to not even bother with the above DataChanged() method and use an anonymous delegate instead, so you could change the MainForm code to look like this:
There are other things you can do when creating your own delegates and/or events and, in fact, I have a written a blog post about a DataAccess class that does some interesting things with anonymous delegates: DataAccess - Part III.
However, expanding on ideas for delegates and/or events is beyond the scope of this simple post. Perhaps in the future I’ll write something more extensive, but in the meantime, you can always start off with an MSDN article such as this one: Handling And Raising Events