0

I have in my opinion thoroughly looked for the answers in this website, but unfortunately I haven't found any or I just suck at looking at it.

I have 2 forms and 1 controller class and 1 model class or data class. In addition, ControllerClass has an array of the model class.

In Form1 I did a reference to the controller like this:

ControllerClass control = new ControllerClass();

In Form2 I want to reference from the ControllerClass I referred to in Form1.

Until now I have been doing something like:

ControllerClass control = new ControllerClass();

in Form2 but this just makes a new copy of the ControllerClass which is not very helpful to me.

So how can I use the ControllerClass that I instantiated in Form1 in Form2?

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • 1
    http://stackoverflow.com/questions/2957388/passing-object-to-different-windows-forms, http://stackoverflow.com/questions/4887820/how-do-you-pass-an-object-from-form1-to-form2-and-back-to-form1, http://stackoverflow.com/questions/1665533/communicate-between-two-windows-forms-in-c-sharp – Corak Oct 12 '13 at 09:36
  • 1
    Just pass the object as an parameter in the constructor of Form2 (`Form2 f2 = new Form2(control);`), or create a public property, which you fill with your object reference. – Daniel Abou Chleih Oct 12 '13 at 09:39

2 Answers2

0

If you only need a single object from a class, you could use a singleton. Then ofc, you will always have the same object.

There are several ways how you can implement your control as a singleton

here some examples: http://csharpindepth.com/articles/general/singleton.aspx

For C# i prefer the nested version.

Silvio Marcovic
  • 495
  • 4
  • 18
-1

If you don't want to pass the object to other forms through the constructor (Communicate between two windows forms in C#), as others have suggested here, you can use a static object within the Form1.

For example, you could declare

public static ControllerClass control = new ControllerClass();

and then access the object like:

ControllerClass temp = Form1.control;

You can also make a second, static, class which will have the ControllerClass object (the class should be in the same namespace and not in the Form1 class), like so:

public static class ControllerStaticClass
{
    public static ControllerClass control = new ControllerClass();
}

Then you can access the ControllerClass object like:

ControllerClass temp = ControllerStaticClass.control;
Community
  • 1
  • 1
Igor Ševo
  • 5,459
  • 3
  • 35
  • 80