Ошибка компилятора cs0120

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0120

Compiler Error CS0120

07/20/2015

CS0120

CS0120

3ff67f11-bdf9-436b-bc0c-4fa3cd1925a6

Compiler Error CS0120

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. For more information about static methods, see Static Classes and Static Class Members. For more information about creating instances of classes, see Instance Constructors.

Example 1

The following sample generates CS0120:

// CS0120_1.cs
public class MyClass
{
    // Non-static field.
    public int i;
    // Non-static method.
    public void f() {}
    // Non-static property.
    int Prop
    {
        get
        {
            return 1;
        }
    }

    public static void Main()
    {
        i = 10;   // CS0120
        f();   // CS0120
        int p = Prop;   // CS0120
    }
}

To correct this error, first create an instance of the class:

// CS0120_1.cs
public class MyClass
{
    // Non-static field.
    public int i;
    // Non-static method.
    public void f() { }
    // Non-static property.
    int Prop
    {
        get
        {
            return 1;
        }
    }

    public static void Main()
    {
        var mc = new MyClass();
        mc.i = 10;
        mc.f();
        int p = mc.Prop;
    }
}

Example 2

CS0120 will also be generated if there is a call to a non-static method from a static method, as follows:

// CS0120_2.cs
// CS0120 expected
using System;

public class MyClass
{
    public static void Main()  
    {  
        TestCall();   // CS0120
   }

   public void TestCall()
   {
   }
}

To correct this error, first create an instance of the class:

// CS0120_2.cs
using System;

public class MyClass
{
    public static void Main()
    {
        var anInstanceofMyClass = new MyClass();
        anInstanceofMyClass.TestCall();
    }

    public void TestCall()
    {
    }
}

Example 3

Similarly, a static method cannot call an instance method unless you explicitly give it an instance of the class, as follows:

// CS0120_3.cs
using System;

public class MyClass
{
   public static void Main()
   {
      DoIt("Hello There");   // CS0120
   }
  
   private void DoIt(string sText)
   {
      Console.WriteLine(sText);
   }
}

To correct this error, you could also add the keyword static to the method definition:

// CS0120_3.cs
using System;

public class MyClass
{
   public static void Main()
   {
      DoIt("Hello There");   // CS0120
   }
  
   private static void DoIt(string sText)
   {
      Console.WriteLine(sText);
   }
}

See also

  • The C# type system

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.

Почему возникает ошибка

LectureForm — это класс формы, таких форм можно создать сколько угодно.

btnNext — это свойство экземпляра класса формы. Это кнопка, которая лежит на конкретном экземпляре формы.

Ошибка говорит о том, что Вы пытаетесь через класс обратиться к свойству объекта этого класса, так делать нельзя.

Общие данные

Т.к. LectureForm показывается отдельно от Param, то обратиться к объекту LectureForm нельзя т.к. форма еще не создана.

В этом случае нужно чтобы Param записала данные куда-нибудь откуда lectureForm может их считать.

Можно например объявить глобальное статическое поле в каком-нибудь классе. Например, в том же Param сделать ему значение по-умолчанию false и изменять его при нажатии на checkbox:

//поле внутри класса `Param`
public static bool LectureFormButtonsVisible = true;

...
//установка в обработчике checkBox
listBox2.Visible = false;

LectureFormButtonsVisible = checkBox1.Checked;

Потом при отображении LectureForm это поле можно будет считать:

private void LectureForm_Load(object sender, EventArgs e)
{
    btnNext.Visible = Param.LectureFormButtonsVisible;
    WMP.Visible = Param.LectureFormButtonsVisible;
}

Как будет время почитайте про проекты проектирования, про то как можно отделить интерфейс от логики. При правильной архитектуре приложения у форм будет доступ к общей модели и они сами будут реагировать на изменение. Построение такой архитектуры сильно зависит от Вашего приложения и, пожалуй, сильно выходит за рамки этого вопроса.

In this tutorial, you’ll learn everything about the error “CS0120 – An object reference is required for the nonstatic field, method, or property ‘member’ in C#, why this error appears in your .NET Code and how you can fix them by following simple steps.

C# Compiler Error

This is how the CS0120 error in C# looks like in general.

CS0120 – An object reference is required for the nonstatic field, method, or property ‘member’

Reason for the Error

You will receive the CS0120 error in C# when you are trying to access an non-static field, property or method from a static class.

For example, the below code snippet contains a non-static property MyProperty defined in the class by name “DeveloperPublish” and you are trying to access this non-static property from a static method (“Main”) defined in the same class.

namespace DeveloperPublishNamespace
{

    public class DeveloperPublish
    {
        public int MyProperty { get; set; }
        public static void Main()
        {
            MyProperty = 1;
        }
    }
}

This will result with the compiler error CS0120.

Error CS0120 An object reference is required for the non-static field, method, or property ‘DeveloperPublish.MyProperty’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 9 Active

C# Error CS0120 – An object reference is required for the nonstatic field, method, or property 'member'

Solution

To fix the CS0120 Error in C#, avoid accessing the non-static member directly from the static method.

I’m getting the error ‘An object reference is required for the nonstatic field, method, or property ‘ when I attempt to run my application in Visual Web Developer. I am not sure what is wrong and I’m new to programming, and I’m following examples from a book. The page allows a logged in user to view their profile which the attributes such as Firstnames, Lastnames etc. are within my web.config file. Does anyone know what I am doing wrong? My error, along with code, is below. Thanks in advance!

Compiler Error Message: CS0120: An object reference is required for the nonstatic field, method, or property ‘System.Web.UI.Control.FindControl(string)’

Source Error:

Line 32:      protected void SaveButton_Click(object sender, EventArgs e)
Line 33:     {
Line 34:         Profile.Firstnames = ((TextBox)LoginView.FindControl("FirstNamesTextBox")).Text;

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

public partial class SecurePage : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (User.Identity.IsAuthenticated == false)

{

Server.Transfer(«login.aspx»);

}

if (!Page.IsPostBack)

{

DisplayProfileProperties();

}

}

protected void CancelButton_Click(object sender, EventArgs e)

{

DisplayProfileProperties();

}

protected void SaveButton_Click(object sender, EventArgs e)

{

Profile.Firstnames = ((TextBox)LoginView.FindControl(«FirstNamesTextBox»)).Text;

Profile.Lastname = ((TextBox)LoginView.FindControl(«LastNameTextBox»)).Text;

Profile.FirstLineOfAddress = ((TextBox)LoginView.FindControl(«FirstLineOfAddressTextBox»)).Text;

Profile.SecondLineOfAddress = ((TextBox)LoginView.FindControl(«SecondLineOfAddressTextBox»)).Text;

Profile.TownOrCity = ((TextBox)LoginView.FindControl(«TownOrCityTextBox»)).Text;

Profile.County = ((TextBox)LoginView.FindControl(«CountyTextBox»)).Text;

}

protected void LoginView_ViewChange(object sender, System.EventArgs e)

{

DisplayProfileProperties();

}

private void DisplayProfileProperties()

{

TextBox FirstNamesTextBox = (TextBox)LoginView.FindControl(«FirstNamesTextBox»);

if (FirstNamesTextBox !=null)

{

((TextBox)LoginView.FindControl(«FirstNamesTextBox»)).Text = Profile.FirstNames;

((TextBox)LoginView.FindControl(«LastnameTextBox»)).Text = Profile.Lastname;

((TextBox)LoginView.FindControl(«FirstLineOfAddressTextBox»)).Text = Profile.FirstLineOfAddress;

((TextBox)LoginView.FindControl(«SecondLineOfAddressTextBox»)).Text = Profile.SecondLineOfAddress;

((TextBox)LoginView.FindControl(«TownOrCityTextBox»)).Text = Profile.TownOrCity;

((TextBox)LoginView.FindControl(«CountyTextBox»)).Text = Profile.County;

((TextBox)LoginView.FindControl(«ContactNumTextBox»)).Text = Profile.ContactNum;

}

}

}

Привет всем.
сегодня хотел сделать нажатие кнопки по нажатию клавиши на клавиатуре, но столкнулся с проблемой которую я не знаю как решать. Надеюсь подскажите как её решить. заранее спасибо
код:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
class MyButtonClass : Form
{

    private Button One, Two, Three, Four, Fife, Six, Seven, Eight, Nine, Zero, Plus, Minus, multiply, division, Equally, dot, Delete, clear, copy, past;
    private TextBox FirstText, SecondText, ThirdText;


    private void InitializeComponent()
    {
        this.SuspendLayout();
        // 
        // MyButtonClass
        // 
        this.ClientSize = new System.Drawing.Size(280, 525);
        this.Name = "MyButtonClass";
        this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
        this.ResumeLayout(false);

    }

    double n, k, res;
    int v, b;

    public MyButtonClass()
    {
        v = 0;
        b = 0;

        Plus = new Button();
        Plus.Text = "+";
        Plus.Top = 150;
        Plus.Left = 210;
        Plus.Height = 100;
        Plus.Width = 70;
        Plus.Click += new System.EventHandler(PlusButton);
        this.Controls.Add(Plus);
        //Declare, properties and call a button

        FirstText = new TextBox();
        FirstText.Text = $"0";
        FirstText.Top = 10;
        FirstText.Left = 0;
        FirstText.Height = 50;
        FirstText.Width = 210;
        this.Controls.Add(FirstText);
        //Declare, properties and call a TextBox

        SecondText = new TextBox();
        SecondText.Text = $"";
        SecondText.Top = 50;
        SecondText.Left = 0;
        SecondText.Height = 50;
        SecondText.Width = 210;
        this.Controls.Add(SecondText);
        //Declare, properties and call a TextBox

        ThirdText = new TextBox();
        ThirdText.Text = $"0";
        ThirdText.Top = 100;
        ThirdText.Left = 0;
        ThirdText.Height = 50;
        ThirdText.Width = 210;
        this.Controls.Add(ThirdText);
        //Declare, properties and call a TextBox

        InitializeComponent();
        this.StartPosition = FormStartPosition.Manual;
        this.Location = new Point(-5, 0);
    }
    [STAThread]
    static void Main()
    {
        Application.Run(new MyButtonClass());
        //starting objects of class MyButtonClass
    }
    void PlusButton(object sender, EventArgs e)
    {

        if (v == 0)
        {
            SecondText.Text = "+";
            v = 1;
        }
        else if (v == 1)
        {

            n = double.Parse(FirstText.Text);
            k = double.Parse(ThirdText.Text);
            if (SecondText.Text == "+")
            {
                res = n + k;
            }
            else if (SecondText.Text == "-")
            {
                res = n - k;
            }
            else if (SecondText.Text == "x")
            {
                res = n * k;
            }
            else if (SecondText.Text == "/")
            {
                res = n / k;
            }
            string r = Convert.ToString(res);
            FirstText.Text = r;
            SecondText.Text = "+";
            ThirdText.Text = "0";
            v = 1;
        }
    }
    public class FilteredTextBox : TextBox
    {
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (e.KeyChar == '+')
            {
                Plus.PerformClick();
                // здесь ошибка
            }
            base.OnKeyPress(e);
        }
    }
}

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора cs0115
  • Ошибка компилятора cs0103
  • Ошибка компилятора cs0030
  • Ошибка компиляции для платы generic esp8266 module
  • Ошибка компилятора cs0029