... edit #1 ... in which Form2 is not derived from Form1 ...
Un_NaMed wrote: "
Quote:
In form 2(derived form), the user will click on a button,
a map will be drawn in Form 1's picturebox.
Okay, let's assume that Form2 is created in Form1:
0. in Form1's code:
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
f2.f2Button.Click += new EventHandler(f2Button_Click);
}
public void f2Button_Click(object sender, EventArgs e)
{
MessageBox.Show("button clicked in Form2 handled in Form1");
}
1. in Form2's code:
public Button f2Button { get; set; }
private void Form2_Load(object sender, EventArgs e)
{
f2Button = this.button1;
f2Button.Click +=new EventHandler(f2Button_Click);
}
private void f2Button_Click(object sender, EventArgs e)
{
MessageBox.Show("button click handled in Form2");
}
If you compile and run this example, in a project where you have created a Main Form, Form1, and added another form, Form2, and added a button on each Form, then you should observe that when the project is run: both Forms appear, and that clicking on the button in Form2 will trigger two events: it will execute the button-click handler on Form2 first and then execute the button-click handler fired on Form1.
... end edit #1 ...
Discussion: You are confusing here two very different issues:
1. inheritance: if you create an instance of Form2 that inherits from Form1: you get an exact copy of Form1: each Form has its own set of identical controls, and they are completely independent of each other.
2. communication across Forms between Controls/Objects: I believe this is what you are asking about, and this is one of the most frequently asked and answered questions here on QA.
The important thing here is to define the nature of the communication required:
1. do you want something on Form2 to raise an Event that Form1 will subscribe to, and pass information in that Event that Form1 can then use ?
2. do you want to achieve "binding:" where whatever is typed, for example, in a certain TextBox in Form2 appears in a TextBox in Form1 ?
3. Or, does some control on Form2 need access to some control on Form1 in order to manipulate it: for example, you might wish a change in selection in a ComboBox drop-down on Form2 to have some effect on a control in Form1.
4. In the case that every control on Form2 requires access to every control on Form1: a different scenario arises: involving injecting a reference to the instance of Form1 into Form2 when it is created, and making controls on Form1 publicly accessible through public properties. This may be loosely called "injection."
The first step is to define exactly the nature of the dynamic links between the controls on Form2 and Form1.
You need to get a good book on C#, like one from Jesse Liberty, and study up on inheritance, events, properties, etc.