First of all, there are two strings there: one is called Value, and the
other is the return value of the delegate method. I'm not sure what the
latter does.
I'm assuming that these two forms are independent. That is, that the
form that needs the value when the OK button is pressed has not
displayed the other form using ShowDialog(). If form1 displays form2
using ShowDialog() like this, then the answer is easy: form2 should
expose a property called WhateverString (or whatever :-), and form1
should query it before disposing of form2:
string resultString = "";
Form2Type form2 = new Form2Type();
if (form2.ShowDialog() == DialogResult.OK)
{
resultString = form2.WhateverString;
}
form2.Dispose();
However, if the two forms are unrelated (form2 is started using Show(),
not ShowDialog()), then the solution is, as you suggested to use an
event. However, I wouldn't use a specific "button pressed" event as
you're suggesting. That strikes me as too much in the "language" of the
insides of form2. What you really want, I think, it to say, "When the
user indicates that he's done with form2, signal form1, so maybe an
event called "Result" would be more appropriate:
public class Form2ResultArgs
{
... just fields, a constructor, and properties to get values out...
}
public delegate void Form2ResultHandler(object sender, Form2ResultArgs
args);
Now, in form2, declare:
public event Form2ResultHandler Result;
and
private void OKbutton_Clicked(object sender, System.EventArgs args)
{
Form2ResultArgs args = new Form2ResultArgs(...the results...);
if (this.Result != null)
{
this.Result(this, args);
}
this.DialogResult = DialogResult.OK;
}
And, in form1 (assuming that you can get your hands on an instance of
Form2... use the Singleton pattern in Form2 if there should only ever
be one):
public Form1()
{
... designer stuff...
... get hands on instance of form2 ...
form2.Result += new Form2ResultHandler(HandleForm2Result);
}
and
private void HandleForm2Result(object sender, Form2ResultArgs args)
{
string resultString = args.ResultString; // or whatever
}