2

I have 2 forms namely: FormA and FormB.

Assume FormA is currently visible and I need to pass data to FormB.

I can do that easily by using constructors ,

 FormB PassToThisForm = new FormB(int Data);
 PassToThisForm.ShowDialog();

Now, my problem is how to get some data from FormB while FormA is CURRENTLY VISIBLE?

I can't to this :

  FormA main = new FormA();

since it will create a new instance of FormA... any idea?

Thanks in advance ^_^

M.Babcock
  • 18,753
  • 6
  • 54
  • 84
nfinium
  • 141
  • 3
  • 8
  • 3
    possible duplicate of [C# beginner help, How do I pass a value from a child back to the parent form?](http://stackoverflow.com/questions/280579/c-sharp-beginner-help-how-do-i-pass-a-value-from-a-child-back-to-the-parent-for) – Mitch Wheat Jan 23 '12 at 01:13
  • 1
    Are you looking to have `FormB` *return* data to form A when it closes (Such that Mitch's suggestion would be valid) or do you need the forms to exchange information while both are active? – M.Babcock Jan 23 '12 at 01:17
  • Im currently reading Mitch's answer.. I'll post my comment if ever I encounter some problem..Thanks mitch – nfinium Jan 23 '12 at 01:24
  • @@John Mark Flores: if my linked answer helped you, please consider upvoting it. – Mitch Wheat Jan 23 '12 at 01:35
  • I tried it but it requires 15 reputation.. – nfinium Jan 23 '12 at 01:58

2 Answers2

1

You could pass a reference to FormA using FormB's constructor.

Your FormB class could look something like this then:

partial class FormB
{

     private FormA reftoA; 

     public FormB(FormA formref, int Data)
     {
          reftoA= formref;
     }

     private void SomeMethodToChangeSomethinginFormA()
     {
              reftoA.SomeProp= 4;
     }
}
Tim Dams
  • 747
  • 1
  • 6
  • 15
0

I have done this previously by having e.g. FormB implement an interface that contains a property for the value from FormA. In the constructor for FormA I declare a parameter for that interface. Then I declare in the dependency injection container that FormB is the implementation passed to FormA for that interface.

public interface ISomeInterface
{
    int SomeProperty { set; }
}

public class FormB : Form, ISomeInterface
{
    int SomeProperty { set; private get; }

    // rest of FormB code
}

public class FormA
{
    private readonly ISomeInterface someInterface;
    FormA(ISomeInterface someInterface)
    {
        if (someInterface == null) throw new ArgumentNullException();
        this.someInterface = someInterface;
    }

    // then in FormA you can refer to someInterface.SomeProperty
}
David Clarke
  • 12,888
  • 9
  • 86
  • 116