How to propagate an Event up to the MainForm?

R

RickL

Hi,

I'm developing a C# Windows Form app, which contains 2 UserControls
in the MainForm. One of the UserControls contains a number of layers
as shown in the following hierarcy:

MainForm
UserControl1 UserControl2
SplitContainer
SplitContainer.Panel1
UserControl3
Button1, Button2, etc

Problem:
When the user clicks a button on UserControl3, I need to pass that
information to UserControl1 on the MainForm. I know how to add an
event for a Button1_Click at the UserControl3 level, but I can't figure
out how to get this event to the MainForm. I've tried many things,
including adding a public ProcessButton() method to the MainForm
and then trying to call it from UserControl3 with 'this.ParentForm.???'.
All to no avail.

Question:
When the user clicks on Button1, how can I propagate this event up
to the MainForm so it can tell UserControl1 to do something?

Thanks for any suggestions,
RickL
 
G

Guest

Hi,

If you make a public getter property for each control on each layer and
finally a public event on the last layer that gets fired from the button
click eventhandler. You can then add an eventhandler to that event by
accessing the right properties in the other layers.

The following code demonstrates this principle.

class Panel1 {
public Panel2 SubPanel {
get { return _panel2; }
}
}

....

class Panel2 {
public event EventHandler Event1;

private void Button1_Click(object sender,EventArgs e) {
if(Event1 != null)
Event1(this,EventArgs.Empty);
}
}
}

....

Class MainForm {
public MainForm() {
_panel1.Panel2.Event1 += new EventHandler(buttonClicked);
}

private void buttonClicked(object sender,EventArgs e) {
//TODO: Do something
}
}

Hope this helps.
 

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