Situation: C#, .NET 3.5, WinForms
Objective: Form1 has a Button that can be enabled via the constructor. I.E. the button will only be shown if I call new Form1(true).
We'd like to be able to pass a method via some param from Form2 to Form1 (doesn't have to be on Form1's constructor), and when Form1.Button1 is pressed, Form2.<SomeMethod>
should be executed.
We know that we could create a Delegate/Event in Form1 and from Form2 do something like:
Form1.SomeDelegate += new ..... (MyMethodInForm2);
…and then in Form1_ButtonClick we fire the event which, in turn will do the magic in Form2.
But we were wondering if there was a more elegant/new/modern version (Anonymous Methods? Lambda Expressions? Etc.) to accomplish this.
The idea is that "any" form could instanciate a Form1 class and pass its own method to be executed when Form1's button is clicked; but instead of a callback to the caller (form2,3,..n), Form1 executes the passed function (which possibly resides inside the caller). We really don't need these functions to have parameters for now.
Note: The code samples contain simple variable/object names and are not taken from real life, please ignore the simplicity.
UPDATE Sorry for not being more specific, I think that I'll keep using the Delegate/Event model, but for reference, here's what I think is a better description of the situtation:
Form1 is a generic form, that accepts a list of items and displays them. We may pass Employee types or Person Types or any "T". It works ok. We received a requirement from a customer, asking if it was possible to add an optional button to that little Form1 that, if clicked, it will open another form/execute some method.
That way, if I am using Form1, I could -at runtime- tell the button to open the EmployeeForm, whereas if I am using Form1, the very same button could open the form PersonForm. Now opening a Form is not the only use we'd have for that button, but that's the caller's problem.
Right now, what I've done is what we've said: delegate/event on that Form1 and on the "calling" form we do a Form1.theEvent += stuff, to subscribe to the event. I just wanted to know if there was a better way to accomplish this, as this is how we'd do it in .NET 2.0 and we have just started using .NET 3.5.