377

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
  • 5,935
  • 6
  • 39
  • 48
huda
  • 4,107
  • 2
  • 21
  • 24

9 Answers9

522

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
  • 18,547
  • 14
  • 94
  • 196
24

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.

Simon Nitzsche
  • 723
  • 6
  • 13
21

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.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
9

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
  • 8,408
  • 6
  • 48
  • 68
issam chouchane
  • 135
  • 1
  • 2
  • 2
    This specific method explicitly accesses instance properties (specifically `this.InvokeRequired` and `this.Invoke`) and so cannot be made static. – dbc Mar 31 '20 at 21:05
5

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());
    }
}
veggiebenz
  • 389
  • 5
  • 12
5

Make the function static. This must solve your problem.

4

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.

Max Alexander Hanna
  • 3,388
  • 1
  • 25
  • 35
4

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)
        }
    }
}
Dean P
  • 1,841
  • 23
  • 23
3

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
  • 30,738
  • 21
  • 105
  • 131