Ошибка an object reference is required for the non static field method or property

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

Что я делаю не так?

Класс-родитель:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
 
namespace Semiconductors
{
    public class OutputArea
    {
        MainWindow form;
 
        public OutputArea(MainWindow f, EventHandler eventHandler)
        {
            form = f;
            Label buttonOK = new Label();
            buttonOK.AutoSize = true;
            buttonOK.Cursor = System.Windows.Forms.Cursors.Hand;
            buttonOK.Font = new System.Drawing.Font("Microsoft Sans Serif", 12, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            buttonOK.Image = global::Semiconductors.Properties.Resources.buttonGreen25_1;
            buttonOK.Size = new System.Drawing.Size(90, 25);
            buttonOK.Location = new System.Drawing.Point(310, 370);
            buttonOK.MaximumSize = new System.Drawing.Size(90, 25);
            buttonOK.MinimumSize = new System.Drawing.Size(90, 25);
            buttonOK.Name = "Close";
            buttonOK.Text = "Закрити";
            buttonOK.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            buttonOK.UseCompatibleTextRendering = true;
            buttonOK.BackColor = Color.Transparent;
            buttonOK.MouseLeave += new System.EventHandler(label_MouseLeave);
            buttonOK.MouseHover += new System.EventHandler(label_MouseHover);
            buttonOK.Click += new System.EventHandler(eventHandler);
            form.Controls.Add(buttonOK);
        }
 
        private void label_MouseHover(object sender, EventArgs e)
        {
            ((Label)sender).Image = Semiconductors.Properties.Resources.buttonGreen25_2;
        }
 
        private void label_MouseLeave(object sender, EventArgs e)
        {
            ((Label)sender).Image = Semiconductors.Properties.Resources.buttonGreen25_1;
        }
    }
}

Унаследованный от него класс:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace Semiconductors
{
    public class OutputTextArea : OutputArea
    {
        MainWindow form;
        RichTextBox richTextBox;
 
        public OutputTextArea(MainWindow f, bool fromFile, string text)
            : base(f, clickClose)
        {
            form = f;
            richTextBox = new System.Windows.Forms.RichTextBox();
            richTextBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(193)))), ((int)(((byte)(255)))), ((int)(((byte)(219)))));
            richTextBox.Cursor = System.Windows.Forms.Cursors.Default;
            richTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            richTextBox.Location = new System.Drawing.Point(72, 82);
            richTextBox.Name = "richTextBox";
            richTextBox.ReadOnly = true;
            richTextBox.Size = new System.Drawing.Size(547, 281);
            LoadText(fromFile, text);
        }
 
        private void LoadText(bool fromFile, string text)
        {
            if (fromFile)
            {
                try
                {
                    richTextBox.LoadFile(MainWindow.currentDirectory + text);
                }
                catch (System.IO.FileNotFoundException)
                {
                    MessBox.Show("Помилка! Не вдалося відкрити файл "" + text
                        + "". Перевірте його наявність в папці з даною програмою.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            else
            {
                richTextBox.Text = text;
            }
            form.Controls.Add(richTextBox);
        }
 
        private void clickClose(object sender, EventArgs e)
        {
            Dispose();
        }
 
        public void Dispose()
        {
            form.labelTitle.Text = MainWindow.title;
            try
            {
                form.Controls.Remove(form.Controls["richTextBox"] as RichTextBox);
                (form.Controls["richTextBox"] as RichTextBox).Dispose();
            }
            catch { }
            form.menu.InitializeMenu();
            richTextBox = null;
        }
    }
}

Ошибка происходит в строчке:

C#
1
2
public OutputTextArea(MainWindow f, bool fromFile, string text)
            : base(f, clickClose)

В чем проблема?



0



Злой няш

2136 / 1505 / 565

Регистрация: 05.04.2010

Сообщений: 2,881

04.05.2012, 21:07

2

Фокус в том, что метод clickClose или Dispose в этот момент не существует, так как объект еще не создан. Даже если сделать clickClose статическим, это не поможет. Проще говоря, вы пытаетесь реализовать бред.



1



tezaurismosis

Администратор

Эксперт .NET

9394 / 4679 / 757

Регистрация: 17.04.2012

Сообщений: 9,521

Записей в блоге: 14

04.05.2012, 21:20

3

Лучший ответ Сообщение было отмечено как решение

Решение

Сделайте Label1 открытым полем:

C#
1
2
3
4
5
6
public class OutputArea
{
    MainWindow form;
    public Label buttonOK;
    //...
}

buttonOK.Click += new System.EventHandler(eventHandler) в OutputArea уберите и в конструкторе OutputTextArea добавьте:

C#
1
base.buttonOK.Click += new EventHandler(clickClose);

Теперь EventHandler не надо передавать конструктору базового класса (уберите его из параметров конструктора).
Если не понятно, вот код, но я его слегка подкорректировал, чтобы он не выдавал ошибок, ведь у меня не вся реализация:

код

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
 
namespace Semiconductors
{
    public class MainWindow : Form
    {
    }
 
    public class OutputArea
    {
        MainWindow form;
        public Label buttonOK;
 
        public OutputArea(MainWindow f)
        {
            form = f;
            buttonOK = new Label();
            buttonOK.AutoSize = true;
            buttonOK.Cursor = System.Windows.Forms.Cursors.Hand;
            buttonOK.Font = new System.Drawing.Font("Microsoft Sans Serif", 12, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            buttonOK.Size = new System.Drawing.Size(90, 25);
            buttonOK.Location = new System.Drawing.Point(310, 370);
            buttonOK.MaximumSize = new System.Drawing.Size(90, 25);
            buttonOK.MinimumSize = new System.Drawing.Size(90, 25);
            buttonOK.Name = "Close";
            buttonOK.Text = "Закрити";
            buttonOK.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            buttonOK.UseCompatibleTextRendering = true;
            buttonOK.BackColor = Color.Transparent;
            buttonOK.MouseLeave += new System.EventHandler(label_MouseLeave);
            buttonOK.MouseHover += new System.EventHandler(label_MouseHover);
            //buttonOK.Click += new System.EventHandler(eventHandler);
            form.Controls.Add(buttonOK);
        }
 
        private void label_MouseHover(object sender, EventArgs e)
        {
            
        }
 
        private void label_MouseLeave(object sender, EventArgs e)
        {
            
        }
    }
 
    public class OutputTextArea : OutputArea
    {
        MainWindow form;
        RichTextBox richTextBox;
        public EventHandler eventHdr;
 
        public OutputTextArea(MainWindow f, bool fromFile, string text)
            : base(f)
        {
            form = f;
            richTextBox = new System.Windows.Forms.RichTextBox();
            richTextBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(193)))), ((int)(((byte)(255)))), ((int)(((byte)(219)))));
            richTextBox.Cursor = System.Windows.Forms.Cursors.Default;
            richTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            richTextBox.Location = new System.Drawing.Point(72, 82);
            richTextBox.Name = "richTextBox";
            richTextBox.ReadOnly = true;
            richTextBox.Size = new System.Drawing.Size(547, 281);
            LoadText(fromFile, text);
            base.buttonOK.Click += new EventHandler(clickClose);
        }
 
        private void LoadText(bool fromFile, string text)
        {
            
        }
 
        private void clickClose(object sender, EventArgs e)
        {
            Dispose();
        }
 
        public void Dispose()
        {
            try
            {
                form.Controls.Remove(form.Controls["richTextBox"] as RichTextBox);
                (form.Controls["richTextBox"] as RichTextBox).Dispose();
            }
            catch { }
            richTextBox = null;
        }
    }
}



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.

  • Ошибка an internal error occurred while attempting to perform this command
  • Ошибка an internal error occurred in rigs of rods
  • Ошибка an internal error has occurred while loading the configuration file
  • Ошибка an error occurred while unpacking unable to write data to disk
  • Ошибка an error occurred while starting the application