Passing parameters to and from a Form object

  • Thread starter Thread starter David K.
  • Start date Start date
D

David K.

Hello,
I am a novice to C#.
Say I have two Windows Form: A and B (not a DialogBox).
Suppose I want from Form A object to create and display Form B object
(passing it parameters).
When closing the Form B object, I would like to get the return parameter/s.
Can anybody show me a way of doing it?

Thanks,
David
 
David,

It's like any other method on any other object. Basically, in the
method of FormA, you would create an instance of FormB. Then, you can show
the form if you wish, calling the show method. However, you said you want
to get values returned. So, what you can do on FormB is have a method that
will show the form, as well as return any values that you need. Forms are
nothing more than objects, and you should treat them as such.

Also, if a form is closed, that doesn't mean that you lose the reference
that you have to it. It just means that it is not being shown (or it has
been destroyed, but that doesn't mean that the object wrapper is destroyed).

Hope this helps.
 
My preferred method is using delegates.
They're basically function/method pointers.
All you have to do is create a method in form1 that is expecting the data from form two (the args).
The delegate you use has to match the args and the return type of the method you want it to point to.
This example sends a reference of a button on form2 back to form1, obviously you can send any type you like.

namespace DelegateTest
{

public delegate void TheDelegate(object);
{
public class Form1 : System.Windows.Form
{
public Form1()
{
}
// this is the method we will point to
private void ReturnMethod(object o)
{
// do great things with object o
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private Form1_Load(object sender, System.EventArgs e)
{
Form2 f2 = new Form2(new TheDelegate(ReturnMethod));
f2.Show();
}
}
public class Form2 : System.Windows.Form
{
private TheDelegate f2Delegate;
public Form2(TheDelegate sender)
{
f2Delegate = sender;
}
private void SomeThingHappens(object sender, System.EventArgs e)
{
object o = sender;
f2Delegate(o); // This will call ReturnMethod in form1 and pass it object o.
}
}
}
}
 
Back
Top