Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I'm getting the following error :

Error 1 An object reference is required for the non-static field, method, or property 'TstProject.frmMain.myvar' C:\DISK_C\CSharp\__tmp\tstproject\tstproject\OneClass.cs 10 12 TstProject

with this code :

frmMain:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TstProject
{
	public partial class frmMain : Form
	{
		// non-static field
		public int zozo;

		public frmMain()
		{
			InitializeComponent();
		}

		private void frmMain_Load(object sender, EventArgs e)
		{
			myvar = 100;

			OneClass oc = new OneClass();
		}
	}
}


OneClass :

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TstProject
{
	class OneClass
	{
		public OneClass()
		{
			int zz = frmMain.myvar;

			zz *= 2;
		}
	}
}


I would like to get the value set in frmMain inside the class OneClass ! how can I do that ?

thanks in advance,
sincerly,
Domi.
Posted
Updated 29-Mar-12 2:35am
v3
Comments
Shahin Khorshidnia 29-Mar-12 8:56am    
If you have any question about the solutions, please comment under the aolution.
Do not ask your new question as a new solution. It wont be answered and will be deleted by editors.

Use a Constructor for the class.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TstProject
{
    class OneClass(int myVar)
    {
        int zz = myVar;
    }
}



and in the Form:

C#
//...
private void frmMain_Load(object sender, EventArgs e)
{
    //myvar = 100;

    OneClass oc = new OneClass(100);
}
//...





But some marginal notes:
1. What is myval? It hasn't been defined.
2. You don't need to use a static variable for this case.
3. What is your plan for zozo?
4. your notation is not standard, for example:
frmMain is in hungarian notation that you should not use.
myvar(?!) what notation does it have? if it's a field or a variable use myVar (camelCasing) and if it's a propertym use MyVar (PascalCasing).

Please look at C# Coding Standards - and Naming Conventions
 
Share this answer
 
v4
Declaring 'myvar' as public static will solve the error:
C#
public partial class frmMain : Form
{
    public static int myvar = 100;
...
 
Share this answer
 
Whatever you are doing, i.e. accessing the private variable defined in the frmMain into another class is wrong approach. Since it is private it is not accessible.

The best way would be to define it as a property in the OneClass.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900