0

I want to call a function update in form1 on click even of button in form2. The update method will make changes to controls in form1. I am using this approach , but when I access it does not give access( when method is non static ) and when I make the method static it asks to make the controls static too which I don't want to. Is there any other way ?

public button1_click()
{

Form1.update();

}

// method in form1

public static void update()
{

 control.Text="ab";

}
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
phpnet
  • 903
  • 1
  • 8
  • 23

1 Answers1

4

You can't access non-static variables in static methods. Refer to the documentation:

While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field.

It is not possible to use this to reference static methods or property accessors.

In this case, if your update method (BTW should be Update) needs to access non-static members of your class, you should make it non-static, and change the Form2 as follows:

1) Add a field and change form's constructor to accept Form1 instance as a parameter:

private Form1 form1;

public Form2(Form1 form1)
{
    this.form1 = form1;
}

2) When creating form2 from form1 pass its instance:

Form2 form2 = new Form2(this); // when in Form1

If you're creating Form2 in some other context you need to (analogically) have form1 instance at hand and call:

Form2 form2 = new Form2(form1);

3) Change the event handler to work on the particular instance of Form1:

public button1_click()
{
    this.form1.update();
}
BartoszKP
  • 34,786
  • 15
  • 102
  • 130