himanshu
himanshu

Reputation: 415

How to access a control in one window form from other form

Sir, I have two window forms, each form has some controls. I want to access control of one form from another form. I have tried two ways- 1- Make controls public and access them. 2- Make public properties getting and setting control according to requirement. But in both the case i have to create the object of first form in order to access the properties or public control. I have instaintiated a socket object and bind it to the local endpoint in the constructor of the first form. Now if I create another object of first form in order to access the control, constructor is fired again and the same code of socket binding in executed which results an exception. Please suggest me what to do ??? Thankssssss....

Upvotes: 0

Views: 1657

Answers (1)

Achilleterzo
Achilleterzo

Reputation: 742

You can do this in many ways...

You can declare some static getter/setter to manage a static instance of the compononent:

private static Type _myObject;
public static Type MyObject
{
   get
   {
      return _myObject;
   }
}

In this case you can access it from evrywere if you only need a specific shared object

MyClass.MyObject.Function();

Or you can define a getter for the whole class:

public class MyClass
{
   static MyClass _myClass;
   public static MyClass Instance { get { return _myClass; } }

   public MyClass()
   {
      _myClass = this;
      ...
   }

   public void Hello()
   {
      Console.WriteLine("CIAO!")
   }
} 

And getting all the methods and properties of the class:

MyClass.Instance.Hello();

You can pass also the class in a constructor, property or function, but i dislike this way...

Upvotes: 2

Related Questions