c# - CS0120: An object reference is required for the nonstatic field, method, or property 'foo'


Translate

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)



All Answers
  • Rita Lee
    Translate

    It looks like you are calling a non static property from a static method. You will need to either make the property static, or create an instance of Form1.

    static void SetTextboxTextSafe(int result)
    {
        label1.Text = result.ToString();
    }
    

    OR

    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);
        }
        Form1 frm1 = new Form1();
        frm1.setTextboxText(result);
    }
    

    More info about this error can be found on MSDN.


  • Translate

    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.


  • Translate

    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.


  • Translate

    Your method must be static

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

  • Translate

    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()); } }

  • Translate

    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.


  • Translate

    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.