For this case, where you want to get a Control of a Form and are receiving this error, then I have a little bypass for you.
Go to your Program.cs and change
Application.Run(new Form1());
to
public static Form1 form1 = new Form1(); // Place this var out of the constructor
Application.Run(form1);
Now you can access a control with
Program.form1.<Your control>
Also: Don’t forget to set your Control-Access-Level to Public.
And yes I know, this answer does not fit to the question caller, but it fits to googlers who have this specific issue with controls.
For this case, where you want to get a Control of a Form and are receiving this error, then I have a little bypass for you.
Go to your Program.cs and change
Application.Run(new Form1());
to
public static Form1 form1 = new Form1(); // Place this var out of the constructor
Application.Run(form1);
Now you can access a control with
Program.form1.<Your control>
Also: Don’t forget to set your Control-Access-Level to Public.
And yes I know, this answer does not fit to the question caller, but it fits to googlers who have this specific issue with controls.
The C# “an object reference is required for the non-static field” error is thrown when an object reference is required for the nonstatic field, method or property..
Install the C# SDK to identify and fix these errors
Introduction to an Object Reference is required for the non-static field
An object reference is required for the nonstatic field, method, or property ‘member’
In order to use a non-static field, method, or property, you must first create an object instance.
Consider the following C# example
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//int[] val = { 0, 0};
int val;
if (textBox1.Text == "")
{
MessageBox.Show("Input any no");
}
else
{
val = Convert.ToInt32(textBox1.Text);
Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));
ot1.Start(val);
}
}
private static void ReadData(object state)
{
System.Windows.Forms.Application.Run();
}
void setTextboxText(int result)
{
if (this.InvokeRequired)
{
this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });
}
else
{
SetTextboxTextSafe(result);
}
}
void SetTextboxTextSafe(int result)
{
label1.Text = result.ToString();
}
private static void SumData(object state)
{
int result;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
delegate void IntDelegate(int result);
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Why is this error happening?
An object reference is required for the nonstatic
field, method, or property
'WindowsApplication1.Form1.setTextboxText(int)
Calling a non static member (a property or method, specifically setTextboxText) from a static method (specifically SumData) is causing this error.
How to fix: Object Reference is required for the non-static field?
1. Make the called member static also:
static void setTextboxText(int result)
{
// Write static logic for setTextboxText.
// This may require a static singleton instance of Form1.
}
2. Create an instance of Form1 within the calling method:
private static void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
Form1 frm1 = new Form1();
frm1.setTextboxText(result);
}
Passing in an instance of Form1 would be an option also.
3. Make the calling method a non-static instance method (of Form1):
private void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing C# errors easier than ever. Sign Up Today!
References
[1] StackOverFlow, 2021. Online: https://stackoverflow.com/questions/498400/cs0120-an-object-reference-is-required-for-the-nonstatic-field-method-or-prop
Tolias28 211 / 135 / 8 Регистрация: 18.08.2010 Сообщений: 1,018 |
||||||||||||
1 |
||||||||||||
04.05.2012, 20:39. Показов 45224. Ответов 3 Метки нет (Все метки)
Есть два класса. Один наследуется от другого. В унаследованном класе пытаюсь перадать в конструктор базового класса ссылку на функцию-обработчик клика мыши, но не пойму почему студия ругается: Error 1 An object reference is required for the non-static field, method, or property ‘Semiconductors.OutputTextArea.clickClose(object, System.EventArgs)’ F:CWProjectSemiconductorsSemiconductorsSemiconductorsOutputTextArea.cs 15 23 Semiconductors Что я делаю не так? Класс-родитель:
Унаследованный от него класс:
Ошибка происходит в строчке:
В чем проблема?
0 |
Злой няш 2136 / 1505 / 565 Регистрация: 05.04.2010 Сообщений: 2,881 |
|
04.05.2012, 21:07 |
2 |
Фокус в том, что метод clickClose или Dispose в этот момент не существует, так как объект еще не создан. Даже если сделать clickClose статическим, это не поможет. Проще говоря, вы пытаетесь реализовать бред.
1 |
tezaurismosis Администратор 9394 / 4679 / 757 Регистрация: 17.04.2012 Сообщений: 9,521 Записей в блоге: 14 |
||||||||||||
04.05.2012, 21:20 |
3 |
|||||||||||
Сообщение было отмечено как решение РешениеСделайте Label1 открытым полем:
buttonOK.Click += new System.EventHandler(eventHandler) в OutputArea уберите и в конструкторе OutputTextArea добавьте:
Теперь EventHandler не надо передавать конструктору базового класса (уберите его из параметров конструктора). код
3 |
211 / 135 / 8 Регистрация: 18.08.2010 Сообщений: 1,018 |
|
06.05.2012, 00:00 [ТС] |
4 |
Blood-Angel, спасибо за наставление. Понял свою ошибку. Я действительно затупил и забыл одну явную вещь, что сперва инициализируется конструктор базового класса, а потом только свой родной) tezaurismosis, спасибо огромное за подробное пошаговое разъяснение и код! Все работает)
0 |
- Remove From My Forums
-
Question
-
This is likely another stupid newbie question but I need to understand this. I created a project and added a class to it. When i tried to access any of the global members of the class I would get the compiler message listed in the subject. Without thinking about it to much I put static qualifiers on all the members and went merrily along my way. Then I got to thinking about it and it didnt make sense to me. A member of a class whether it be a method an object or a primitive should be accessible to all methods in the class.
Looking at other projects Ive done in c# this seems to be the case. This was the first time though that I added a new class from scratch to a project and Im now wondering what I did wrong.
Here is a very basic code sample of the class I created. If it makes any difference this class is used for the thread thats doing all the work in a Windows Service. The OnStartup method of LLScan creates the thread.
namespace LLScan
{
public class LLSCanJob
{
private static System.DateTime scanDate;
private static string strDate = «»;
private static string logfileName = «»;
private static System.IO.FileStream logFile;
private static System.IO.StreamWriter sw;
public static void threadProcess()
{
//Debugger.Launch();
openLogFile();
getScanTarget();
try
{
while (true)
{
// check if we have work to do.
System.DateTime dt = System.DateTime.Now;
if (dt > scanDate)
{
}
Thread.Sleep(30000); // Check if we need to wake up every 30 seconds.
}
}
catch
{
}
finally
{
// This code will be hit for sure when the Thread.Abort method is executed.
sw.Flush();
sw.Close();
}
}
Anyone care to enlighten this confused newbie ?
Answers
-
If you have a variable in a class which is just declared «private», an instance of that variable is only created when an instance of the class is created. For example:
public class Person
{
private string name;public void PrintName()
{
Console.WriteLine(name);
}
}Person person1 = new Person();
Person person2 = new Person();Now person1 has a string variable called name, and person2 has a different instance.
The PrintName method is also bound to the instance of the class with which it is called, so if you call person1.PrintName(), it will output person1.Name, and if you call person2.PrintName(), it will output person2.name.
A static method, on the other hand, is not bound to any instance of the class; it exists within the class itself. The class doesn’t have an instance of the «name» variable because it wasn’t declared static. So the static method needs to be given an instance of the class to work against, e.g.:
public class Person
{
…
public static void PrintName(Person person)
{
Console.WriteLine(person.name);
}
}I don’t know if I’ve explained that very well.