Here is a simple example:
I have two forms. Form 1 and Form 2. Form 2 is opened by pressing a button on form 1. Form 1 also contains a method that might be called by form 2. So you usually pass a reference as follows
public partial class Form1 : Form{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(this);
form2.Show();
}
public void showMessage()
{
MessageBox.Show("from form1");
}
}
Now in Form2 I have
public partial class Form2 : Form{
Form1 _parent = null;
public Form2(Form1 frm)
{
InitializeComponent();
_parent = frm;
}
private void button1_Click(object sender, EventArgs e)
{
_parent.showMessage();
}
Now this works fine. However, what if you need to open Form2 from a different form?? The name of Form1 is hard coded in Form2. What if I have a form34 that needs to show form2 also? Do I need another copy of form2?
In other words, I need to have code in Form2 that does not explicitly state the calling parent form but rather give me the name of it and then I can have logic to determine what the calling form was and then call an appropriate method in the calling form. How could I do this?
Thanks