In your code example, you create an
instance of a Form in a Button Click EventHandler. That "instance" (object) will cease to exist once the EventHandler code is exited; you will have no reference to it.
Assuming you want the user to enter some information on a Form, and then you want to get that information from another Form, there are several strategies, and OriginalGriff has an excellent series of three articles here on some of those strategies: [
^].
An example of a strategy ... which I hope will complement the ones outlined by OriginalGriff follows:
1. in the Main Form:
private Form2 f2;
private void Form1_Load(object sender, EventArgs e)
{
f2 = new Form2();
f2.SendDataAction += SendDataAction;
}
private void btnShowForm2_Click(object sender, EventArgs e)
{
f2.Show();
}
private void SendDataAction(string tboxtxt, int cboxitmndx, string cbxitmtxt)
{
}
2. In the second Form ... assume there's a TextBox 'textBox1, a Button 'btnSendData, and a ComboBox 'comboBox1 :
public Action<string,> SendDataAction {set; get; }
private void btnSendData_Click(object sender, EventArgs e)
{
if (SendDataAction != null)
{
SendDataAction(textBox1.Text, comboBox1.SelectedIndex, comboBox1.SelectedText);
}
}
What happens here:
1. in Form2 a Delegate (Action) that takes three parameters, a string, an int, and a string, is defined as a Public Property.
1.a. when the 'btnSendData is clicked, if the Action is not null (has subscribers), the Action is invoked, passing the values from the TextBox and ComboBox Controls.
2. in Form1, you'll note that after creating the instance of Form2 'f2, then we can subscribe to the Action/Event on Form2 by passing a reference to the method we create 'SendDataAction ... by using the += operator, we add a method to its InvocationList.
2.a. so, the 'SendDataAction method we defined in Form1 will get invoked by the Button click in Form2, and will receive the data.
Keep in mind that "one size does not fit all:" in other circumstances you may wish to retrieve the data in the second Form "on demand" when some event occurs in the first (Main) form. That calls for another strategy. You may wish to force the second Form to notify the first Form when the user closes it, passing whatever data has been entered.
One reason for "formalizing" transfer of data from one context (Form) to another ... as shown here ... is to achieve "encapsulation," to avoid any possibility that anything that happens on the second Form can somehow "screw up" the first Form, and, the reverse.
The second Form "has no idea" what/how-many subscribers there are to the 'SendDataAction Action/Event: it's just going to "broadcast" to all of them.
Note: 'Action and 'Func are alternative ways of writing (syntax for) a Delegate added to .NET with .NET 3.5. As with all Delegates, they are multi-cast (support multiple subscribers).