user1853846
user1853846

Reputation: 55

An object reference is required for the nonstatic field, method, or property 'member'

`I want to change a textbox text in a static method. how can I do that, considering that i cannot use "this" keyword in a static method. In another words, how can I make an object refrence to a the textbox text property?

this is my code

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public delegate void myeventhandler(string newValue);


    public class EventExample
    {
        private string thevalue;

        public event myeventhandler valuechanged;

        public string val
        {
            set
            {
                this.thevalue = value;
                this.valuechanged(thevalue);

            }

        }

    }

        static void func(string[] args)
        {
            EventExample myevt = new EventExample();
            myevt.valuechanged += new myeventhandler(last);
            myevt.val = result;
        }

  public  delegate string buttonget(int x);



    public static buttonget intostring = factory;

    public static string factory(int x)
    {

        string inst = x.ToString();
        return inst;

    }

  public static  string result = intostring(1);

  static void last(string newvalue)
  {
     Form1.textBox1.Text = result; // here is the problem it says it needs an object reference
  }



    private void button1_Click(object sender, EventArgs e)
    {
        intostring(1);

    }`

Upvotes: 3

Views: 2243

Answers (2)

Abdusalam Ben Haj
Abdusalam Ben Haj

Reputation: 5433

You got a perfect answer from dasblinkenlight. Here is an example of the 3rd method :

public static  string result = intostring(1);

static void last(string newvalue)
{
    Form1 form = (Form1)Application.OpenForms["Form1"];
    form.textBox1.Text = result;
}

I'm not entirely sure why you are passing a string parameter and not using it though.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

If you want to change an attribute of a non-static object from inside a static method, you need to obtain a reference to that object in one of several ways:

  • The object is passed to your method as an argument - This one is most common. The object is an argument of your method, and you call methods/set properties on it
  • The object is set in a static field - This one is OK for single-threaded programs, but it is error-prone when you deal with concurrency
  • The object is available through a static reference - This is a generalization of the second way: the object may be a singleton, you may be running a static registry from which you get an object by name or some other ID, etc.

In any case, your static method must get a reference to the object in order to examine its non-static properties or call its non-static methods.

Upvotes: 3

Related Questions