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

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Consider:

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 occurring?

An object reference is required for the nonstatic field, method, or property ‘WindowsApplication1.Form1.setTextboxText(int)

VertigoRay's user avatar

VertigoRay

5,9556 gold badges39 silver badges48 bronze badges

asked Jan 31, 2009 at 6:22

huda's user avatar

It looks like you are calling a non static member (a property or method, specifically setTextboxText) from a static method (specifically SumData). You will need to either:

  1. If you can, make setTextboxText static:
    static void setTextboxText(int result)

HOWEVER, in this case, setTextboxText REQUIRES access to instance variables, so cannot be static.
Instead do:

  1. Call setTextboxText via a static singleton of Form1:
class Form1
{
    public static Form1 It;   // Singleton.

    public Form1()
    {
        It = this;
    }

    private static void SumData(object state)
    {
        ...
        It.setTextboxText(result);
    }
}
  1. 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);
    }
    

    BUT that won’t do what you want, if an instance of Form1 already exists.
    Passing in an instance of Form1 would be an option also.

  2. 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);
     }
    

More info about this error can be found on MSDN.

ToolmakerSteve's user avatar

answered Jan 31, 2009 at 6:28

0

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.

answered Jan 7, 2017 at 20:28

Simon Nitzsche's user avatar

You start a thread which runs the static method SumData. However, SumData calls SetTextboxText which isn’t static. Thus you need an instance of your form to call SetTextboxText.

answered Jan 31, 2009 at 8:40

Brian Rasmussen's user avatar

Brian RasmussenBrian Rasmussen

115k34 gold badges221 silver badges317 bronze badges

2

Your method must be static

static void setTextboxText(int result)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result }); 
    }
    else
    {
        SetTextboxTextSafe(result);
    }
}

PiotrWolkowski's user avatar

answered Jul 1, 2014 at 13:16

issam chouchane's user avatar

1

Credit to @COOLGAMETUBE for tipping me off to what ended up working for me. His idea was good but I had a problem when Application.SetCompatibleTextRenderingDefault was called after the form was already created. So with a little change, this is working for me:


static class Program
{
    public static Form1 form1; // = new Form1(); // Place this var out of the constructor

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(form1 = new Form1());
    }
}

answered Jul 27, 2018 at 2:34

veggiebenz's user avatar

veggiebenzveggiebenz

3895 silver badges12 bronze badges

Make the function static. This must solve your problem.

answered Oct 1, 2021 at 10:19

Sreenath Sreenivasan's user avatar

0

I actually got this error because I was checking InnerHtml for some content that was generated dynamically — i.e. a control that is runat=server.

To solve this I had to remove the «static» keyword on my method, and it ran fine.

answered Jun 3, 2019 at 15:17

Max Alexander Hanna's user avatar

The essence, and solution, to your problem is this:

using System;

namespace myNameSpace
{
    class Program
    {
        private void method()
        {
            Console.WriteLine("Hello World!");
        }

        static void Main(string[] args)
        {
            method();//<-- Compile Time error because an instantiation of the Program class doesnt exist
            Program p = new Program();
            p.method();//Now it works. (You could also make method() static to get it to work)
        }
    }
}

answered May 2, 2021 at 0:05

Dean P's user avatar

Dean PDean P

1,84123 silver badges23 bronze badges

From my looking you give a null value to a textbox and return in a ToString() as it is a static method. You can replace it with Convert.ToString() that can enable null value.

Peter Mortensen's user avatar

answered Jan 12, 2013 at 12:20

Abd Al-Kareem Attiya's user avatar

Getting this error when I submit my form to savetext.aspx action file:

Compiler Error Message: CS0120: An object reference is required for the nonstatic field, method, or property 'System.Web.UI.Page.Request.get'

On this line:

string path = "/txtfiles/" + Request.Form["file_name"];

Whole code:

<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>

<script runat="server">

class Test 
{
    public static void Main() 
    {
        string path = "/txtfiles/" + Request.Form["file_name"];
        if (!File.Exists(path)) 
        {
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine(request.form["seatsArray"]);
            sw.WriteLine("");
            }   
        }

        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }
    }
}
</script>

How do I fix it?

Thanks!

asked Jul 14, 2010 at 14:48

IceDragon's user avatar

6

Remove this Test class as well as the static Main method and replace it with a Page_Load instance method like so:

<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e) 
    {
        string path = "/txtfiles/" + Request.Form["file_name"];
        if (!File.Exists(path)) 
        {
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine(Request.Form["seatsArray"]);
                sw.WriteLine("");
            }   
        }

        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Response.Write(s);
            }
        }
    }
</script>

Also you probably want to output to the HttpResponse instead of a console in a web application. Another remark is about your file path: "/txtfiles/", NTFS usually doesn’t like such patterns.

answered Jul 14, 2010 at 14:53

Darin Dimitrov's user avatar

Darin DimitrovDarin Dimitrov

1.0m271 gold badges3288 silver badges2930 bronze badges

0

Darin Dimitrov gave you a hint in right direction, but i want just to give answer to question why does this error happen. Normal error should be:

The name ‘Request’ does not exist in
the current context

This happen because for each aspx file a class is created that inherits from Page by default. All new classes defined inside aspx file become nested classes of that one. Request is member of class Page and this particular error happen because you try to access it from static method of nested type.

answered Jul 14, 2010 at 15:13

Andrey's user avatar

AndreyAndrey

59.1k12 gold badges120 silver badges163 bronze badges

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;

}

}

}

Студворк — интернет-сервис помощи студентам

Здравствуйте, начал изучать C# и ООП, соответственно.
Использую для этого VS 2010.

Вот код, в котором возникает ошибка:

Кликните здесь для просмотра всего текста

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication4
{
    public abstract class Vehicle
    {
 
    }
    public abstract class Train : Vehicle
    {
    }
    public abstract class Car : Vehicle
    {
    }
    public class Compact : Car, IPassengerCarrier
    {
    }
    public class SUV : Car, IPassengerCarrier
    {
    }
    public class Pickup : Car, IHeavyLoadCarrier
    {
    }
    public class PassengerTrain : Train, IPassengerCarrier
    {
    }
    public class FreightTrain : Train, IHeavyLoadCarrier
    {
    }
    public class DoubleBogey424 : Train, IHeavyLoadCarrier
    {
    }
    public interface IPassengerCarrier
    {
    }
    public interface IHeavyLoadCarrier
    {
    }
    class Program
    {
        string Show(Vehicle inside)
        {
            return inside.ToString();
        }
        static void Main(string[] args)
        {
            DoubleBogey424 TrainType1 = new DoubleBogey424();
            FreightTrain TrainType2   = new FreightTrain();
            PassengerTrain TrainType3 = new PassengerTrain();
            Pickup CarType1           = new Pickup();
            SUV CarType2              = new SUV();
            Compact CarType3          = new Compact();
            Console.Beep(100,100);
            Console.WriteLine(Show(TrainType1));
            Console.ReadKey();
        }
    }
}

Скрин, ошибки:

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

Натыкаюсь на неё уже не впервые, однако не могут понять, в чем проблема.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка компас не удалось открыть документ
  • Ошибка кода 5017 tp link
  • Ошибка компилятора cs0115
  • Ошибка компилятора cs0030
  • Ошибка компаса kui1 dll

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: