hi i have this lines of code that i cant make it work
the goal is simple setting the form1 to visible = false
public static void DoActions(string Cmd){
if(Cmd == true)
{
MainForm.Visible = false;
}
}
but i keep on having this error
An object reference is required for
the non-static field, method, or
property
usually i set the called methond to static.. so the error will go away
but on this case how do i do it?
thanks for any help guys
‘System.Windows.Forms.Control.Invoke(System.Delegate)’
This is happening because
DoActionsis a static method rather than an instance method, howeverMainFormis an instance field / property. The distinction is that instance methods operate on an instance of the class on which they are defined, wheras static methods do not.This means that wheras instance methods are able to access properties, fields and methods of their containing class through the
thiskeyword, for example:You cannot do the same thing from inside a static method (think about it, what instance would it operate on?). Note that C# will implicitly assume the use of the
thiskeyword in places where it makes sense (so the above example could have been written asForm1 frm = MainForm).See C# Static Methods for an alternative explanation of static vs instance methods (this is an important concept in object oriented programming that you should take the time to understand properly).
In your example you probably want to change
DoActionsto an instance method (by removing the static declaration):This will allow it to access the instance
MainFormfield / property, however this may cause problems elsewhere in your code in places where you attempt to callDoActionsfrom another static method without supplying an object instance.