New to c# - accessing a property of a form

  • Thread starter Thread starter Dan
  • Start date Start date
D

Dan

I am declaring a property in a form - simplified example below.

public class frmMain : System.Windows.Forms.Form
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
// etc

I am then trying to access that property from another form on a button
click:

frmMain.X = "hello world";

However I get the following compiler error;

"An object reference is required for the nonstatic field, method, or
property "

Does anyone have any suggestion in how to fix.

Thanks in Advance

Dan
 
Dan said:
I am declaring a property in a form - simplified example below.

code snipped...
I am then trying to access that property from another form on a button
click:

frmMain.X = "hello world";

However I get the following compiler error;

"An object reference is required for the nonstatic field, method, or
property "

Does anyone have any suggestion in how to fix.

Thanks in Advance

Dan

You referred to the class name, and not an object. So first you must have
something like...

frmMain mainForm = new frmMain();
mainForm.X = "hello world";

In the above code, frmMain is the name of the class you want to create, and
mainForm is the name of a variable of type frmMain. The new keyword creates
a new object for you, and then you can refer to all properties and methods
in the class through the variable mainForm.

HTH,
Eric
 
Hi,
As the error message explains, the property X in your example is a
member property; as such, it must me called in the context of an
instance of that class.
On the other hand, static methods must be called in the context of the
class.
Given that, you have to correct your code as follows:

public class frmMain : System.Windows.Forms.Form
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
// etc


frmMain mainForm = new frmMain();
mainForm.X = 25;
int x = mainForm.x;

Hope this helps,

Ramiro
 
Back
Top