Sever
Sever

Reputation: 2636

C# obtain existing Form1 instance from static method in Form1

I know its very easy question, but nobody can give simple answer.

Obtain existing Form1 instance from static method in Form1

public partial class Form1 : Form
{
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        callMethod();           
    }

    public static void callMethod()
    {
       // how can get existing Form1 instance here ?             
       statusLabel.Text = "test";
    }
}

Please, it isn't important why I need this, but important to know how.

Upvotes: 2

Views: 1787

Answers (3)

DevEstacion
DevEstacion

Reputation: 1967

you can do it like this though i'd still suggest seperating or creating a model for the values you need and pass it around. See the message concept of .net

public static Form1 Instance
{
   get
   {
      return instance;
   }
}

and add this to your constructor

    private static Form1 instance;
    public Form1()
    {
        instance = this;
        InitializeComponent();
    }

Upvotes: 5

Sangram Nandkhile
Sangram Nandkhile

Reputation: 18192

The keyword 'this' returns a reference to the current instance of the class containing it.

Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class.

You cannot really access any member unless you make them static. In your case assuming statusLabel is textbox, it won't allow you to access it insider a static method.

either make your function non static or you can use something like following code.

callMethod(statusLabel);  

public static void callMethod(Label txt)
 {

    txt.Text = "test";
 } 

Upvotes: 0

Hafiz
Hafiz

Reputation: 194

You can pass Form1 as parameter to callMethod

public static void callMethod(Form form1)
{

   form1.doSomething(); //use Form1 instance
   statusLabel.Text = "test";

}

and you can pass Form1 instance to it. For example, you can call it below if called from within Form1 e.g: on one of it's member function :

Form1.callMethod(this);

however if you want to call it somewhere where you don't hold instance of Form1 thus cannot pass it as argument, you can try to use Singleton pattern instead, so you can code it is a below :

public static void callMethod()
{

   Form1.instance().doSomething(); //use Form1 instance
   statusLabel.Text = "test";

}

Upvotes: -1

Related Questions