help defining callback function
I am coding a user control. On that user control I have a dynamically created 2D array of buttons. What I want is for the user control to have a function that takes a parameter (callback function) so that when one of the buttons on the user control is clicked the callback function on the container form will be called.
This way the click event code will be written in the current project instead of the user having to modify the code in the user control.
Does that make sense?
Re: help defining callback function
In your user control you would provide code something like this:
Code:
private EventHandler clickHandler;
public void SetButtonClickHandler(EventHandler clickHandler)
{
this.clickHandler = clickHandler;
}
Whenever you add a button to the user control you would then just set the Click event handler like this:
Code:
Button myButton = new Button();
myButton.Click += this.clickHandler;
You would then have code like this in your form to provide the event handler:
Code:
private void userControlButtonClick(object sender, System.EventArgs e)
{
MessageBox.Show("A user control button was clicked.");
}
private void button1_Click(object sender, System.EventArgs e)
{
this.myUserControl.SetButtonClickHandler(new EventHandler(this.userControlButtonClick));
}
Edit:
I have tested this with two controls on the same form, but I don't see why it should be any different when one is part of a user control.
Re: help defining callback function
if you want events look at my reply to yesterday's post also
http://www.vbforums.com/showthread.php?t=357956
an idea: if you use an event property,when the user adds a Click event to the user control, you could go through the loop of your 20 buttons and add that same event to all the button.click events.
ie
PHP Code:
private event EventHandler myEvent;
public event EventHandler MyEvent
{
// add event handler
add
{
myEvent += value;
// loop through all your controls and add the same event to them
}
// remove event handler
remove
{
myEvent -= value;
// loop through all your controls and remove the same event form them }
}