Calling a form function from a button click on a user defined control placed on the form

  • Thread starter Thread starter Scott Schade
  • Start date Start date
S

Scott Schade

I have a form onto which I add a control during execution. The control is a
control that I wrote. The control has a number of controls on it. I would
like to click on a button on the control and execute a function on the form.
Is this possible?

Thanks,

Scott
 
You should have your control raise an event when the button is clicked, then
have the form run the method when the event is fired. Similar to how a
button click on a form now works (the button raises the click event, and the
form attaches to that event)

///My control that has a button on it
public class MyControl : UserControl
{
.....
public event EventHandler ButtonClicked;
....
//traps the button press on and raises our event
public void Button1_Clicked(object sender, EventArgs e)
{
if( ButtonClicked != null)
{
ButtonClicked(this, null);
}
}
....
}


//My form that I've put a "MyControl" on
public class Form1 : Form
{
...
...
public void MyControl1_ButtonClicked(object sender, EventArgs e)
{
RunMyMethod();
}
}

note that in the form code, you'll have to attach a delegate to the
MyControl instance's ButonnClicked event. If you use the Windows forms
designer, you can have it do this for you. Drag an instance of your control
to the form, and make sure it's selected. In the property window, view
events (press the lightning bolt symbol), and double-click on the
ButtonClicked event. the stub for the event handler should be created for
you.
 
Hi,

What Philip said (wrote) is exactly the right way to do it. However, there
are chances that the question Scott actually wants to ask "How to get a
reference to the form the user control has been placed on"?
If this is the question the answer is the Control's FindForm() method.
 
Hi Scott,

Does the community's reply make sense to you?

If you still have anything unclear, please feel free to tell me, I will
help you. Thanks

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
Back
Top