1

I have the following method

public partial class formTabelasPsi : Form
{

    private Form1 Opener { get; set; }

    public formTabelasPsi(Form1 opener)
    {
        this.Opener = opener;
        InitializeComponent();
    }

     public static void publicmethod1(string path)
     {
     //some code related to path

     }
}

I want publicmethod1 to check a checkbox whenever this formTabelasPsi runs it.

I tried to specify it using formTabelasPsi.checkBox1.Checked = true; but the code says a object reference is required.

Maybe this is a newbiez question for most of you, but honestly, as a amateur programmer I didn't find this clearly anywhere.

ng80092b
  • 621
  • 1
  • 9
  • 24
  • What form is this code attached to? – Bob Tway Apr 08 '15 at 12:57
  • 4
    You can't access a class member from a static method. How do you expect publicmethod1 to be used in practice? Why are you making it static? – Steve Mitcham Apr 08 '15 at 12:58
  • Because if I don't make it static, when I use it on form1 it will deliver a error saying a object reference is required for the non static field, method or etc... called publicmethod1 @SteveMitcham – ng80092b Apr 08 '15 at 13:31

1 Answers1

2

The checkbox belongs to an instance of that form, you need to reference that instance in order to update it

 public void publicmethod1(string path)
 {
     this.checkBox1.Checked = true;
 }

The method also needs to belong to an instance of the form, you can find out more about instances here

Sayse
  • 42,633
  • 14
  • 77
  • 146
  • not true, the method is `static` and therefore he doesn't accept the `this` keyword, i tried that :p – ng80092b Apr 08 '15 at 13:07
  • 1
    @ng80092b - look at his code sample again, he removed the static keyword. If you must make the method static then you have to pass in an anstance of your class formTabelasPsi. As Sayse pointed out, static members do not have direct access to instance members. – Igor Apr 08 '15 at 13:24
  • @ng80092b - See the link included in my answer, the method shouldn't be static either, you could always pass in an instance of your form through the parameters but at some point, you are going to need to come in with an instance to get the instances properties/fields. So you may as well just start with the instance in the first place – Sayse Apr 08 '15 at 13:36