This is a very simple question yet I couldn't find a solution for it (I am not a pro programmer sorry if this is primitive!). In Form1 I have a variable called "A" and it's value is 1. I send this to Form2 and change the value to 2. And on Form2 closing I need to send the updated value to Form1. This last part I don't know how to do that and I need your help. How can I retrieve the updated value of variable A on form2 closing?
If you have a value that is changed by Form2, and that value is managed by Form2, you can expose it as a property of Form2, e.g.
public class Form2
{
public string MyValue
{
get { return myValue; }
}
}
and then you can retrieve it like
Form2 f2 = new Form2();
f2.ShowDialog();
string theValue = f2.MyValue;
In general you may want to check the DialogResult returned by ShowDialog() to see if the user pressed e.g. the OK or Cancel button. I'm not sure if you need that in this particular case.
UPDATE
If Form2 is not a dialog, you can instead use a callback pattern to inform Form1 that Form2 is closing to allow Form1 to retrieve any values that it needs from Form2. Alternatively you can have the callback directly supply the value you need.
Specifically, you could pass a Func<T>
to Form2 that points to a callback method in Form1. Form2 would then call that Func<T>
when it determines that it is closing. Here, T
represents the type of variable that you want passed back to Form1.
Here's an example that assumes T
is a string:
public Form2 : Form
{
public void MyCallback(string value) { /* Do something with value */
}
public Form1 : Form
{
Func<string> callback;
public Form1(Func<string> callback)
{
this.callback = callback;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (callback != null) callback(myValue);
}
}