You are creating a
new instance of Form1 every time the user clicks button2 in Form2; my guess is that you are never making that instance visible by calling 'Show on it.
If Form2 is your Main Form, and creates Form1, then create
one instance of Form1: in the Load EventHandler for Form2, make it visible with 'Show, and then you'll find that your button2 Click EventHandler will do the right thing: Example 1:
Form1 InstanceOfForm1 = new Form1();
private void Form2_Load(object sender, System.EventArgs e)
{
InstanceOfForm1.Show();
}
private void button2_Click(object sender, EventArgs e)
{
InstanceOfForm1.itemToAddChanged = "foo x 2";
}
However, if Form1 is your main Form, and Form1 creates Form2, a different strategy is called for: Example 2:
Form2 InstanceOfForm2 = new Form2();
private void Form2_Load(object sender, System.EventArgs e)
{
InstanceOfForm2.InstanceOfForm1 = this;
InstanceOfForm2.Show();
}
public Form1 InstanceOfForm1;
private void button2_Click(object sender, EventArgs e)
{
InstanceOfForm1.itemToAddChanged = "foo x 2";
}
However, there are better ways to handle the case where Form1 is the Main Form, and creates Form2, such as: exposing only the ListBox on Form1 to Form2, or writing a custom Event that is fired in Form2 when button2 is clicked, and which is subscribed to by Form1.
Another alternative is to expose Button2 on Form2 to Form1; then Form1 can subscribe to the Click Event of button2: Example 3:
Form2 InstanceOfForm2 = new Form2();
private void Form1_Load(object sender, System.EventArgs e)
{
InstanceOfForm2.Form2Button2 .Click += Form2Button2_Click;
InstanceOfForm2.Show();
}
private void Form2Button2_Click(object sender, EventArgs e)
{
itemToAddChanged = "foo x 2";
}
public Button Form2Button2 { set; get; }
private void Form2_Load(object sender, EventArgs e)
{
Form2Button2 = this.button2;
}
In the second example, the instance of Form1 was exposed to the instance of Form2; in the third example, only the ListBox on Form1 was exposed to Form2. And, the third example makes the assumption that Form2 does not need to "pass" to Form1 different text messages, which is, quite possibly, incorrect.
Hopefully, you'll get some ideas from these examples. There are even more ways to achieve inter-form communication (such as via the use of Interfaces, or the insertion of dynamic pointers Action, Func into Classes). imho, a good principle to follow is to try and expose to the "outside" of any given Form (or Object) only the minimum necessary for a given task; this increases the modularity of your code, and reduces potential for errors, and puzzling side-effects.
May I suggest that you will learn more if you write out, and test, yourself, an example where Form2 raises a custom Event which is subscribed to by Form1, and an example where Form1 exposes only the ListBox to Form2.