Call an event handler on a parent form from child form

J

jimcolli

I have a parent form with a menu button that has a handler.
I want to call this same handler when a button on a child form is
clicked.

I have this simplified code in the main form's Load handler.

public class frmMain
{

private System.Windows.Forms.Button btnClickMe;

private void frmMain_Load(object sender, System.EventArgs e)
{
// Following instance becomes visible when a menu
// button is clicked.
ChildForm frmMyChild = new ChildForm ( );

// ...
}

// ...
// (Windows Form Designer generated code)
// ...
private void btnClickMe_Click (object sender, System.EventArgs e)
{
// do some complicated stuff here
Console.WriteLine ("btnClickMe was clicked."

}


On the child form, I have another button which we'll call btnClickMeToo
with the usual click handler,

void btnClickMeToo_Click(object sender, System.EventArgs e)
{

}

I want this main form to "listen" to btnClickMeToo as well and
execute the code in its btnClickMe_Click handler when
it is clicked. The console message makes clear that
the event from the child form's button was handled.

I know I'm overlooking something fundamental here.
Anyone know how to do this?
 
J

jimcolli

I have a parent form with a menu button that has a handler.
I want to call this same handler when a button on a child form is
clicked.

A correction here. The menu handler makes the
child form visible, and creates a new instance of it
it has been disposed.

The Click Me button the main form has handler
that among other things writes a one-liner to the
console. It is *this* handler I wish to call when a
button on the child form is clicked.
 
C

Coder

Try this...

frmChild.btnClickMeToo.Click += new
EventHandler(frmMain.btnClickMe_Click);

This will make it so that when the child button is clicked, the main
form will also handle it.
 
J

jimcolli

Coder said:
Try this...

frmChild.btnClickMeToo.Click += new
EventHandler(frmMain.btnClickMe_Click);

This will make it so that when the child button is clicked, the main
form will also handle it.

Thanks, Coder! Yes, that does do it. And if
the child form has been disposed, a new event handler
entry is necessary, too, I presume.

You know, the simple question I should have asked
(I mention it here so that someone will find it in a Google
search) is:

"How do I make one event handler handle
multiple events where the events are buttons
clicked on different forms?"


Jim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top