I have a class that creates an instance of a form with several buttons. I have a function in this class which is meant to wait for the user to click one of the buttons and return different values depending on which button was pressed. I’ve read some of the stuff on using anonymous delegates for this, but I’m not sure how I would determine which specific button was pressed. My original approach was to create a custom event that takes the button number as parameter, and tacking an event handler onto that from my class, but again I am not sure how I would have that function return anything once I get into a delegate.
Is there any straightforward way of doing this?
PM
Assuming WinForms, there are a few approaches you could take. You could expose each button as a property on your form class and have the class the creates the form subscribe to the Click event for each button. For example,
In the Form class:
In the class that creates the form:
Alternatively, you could add a ButtonClicked event to the Form and determine which button was pressed that way. The form would subscribe to each of its button’s Click events and fire ButtonClicked with button as the sender.
I’d probably go with the former since it would avoid having to write an if statement to determine which button was pressed.
Edited to adapt to the workflow in comments:
In that case, what you can do is have the Form take care of some of the details for you. For example, have the form record which button was pressed. If you show the form as a modal dialog, that will by design block the function that’s created the form until it is dismissed.
Calling code:
Note that the HandleButtonClicked event handler is the same for both buttons, since the form is just storing which button was clicked.