Rob

Rob

  • NA
  • 12
  • 0

Calling a method from another form

Jul 22 2008 6:51 PM

Hey,

I have a windows form and im trying to call a method from another form but im struggling because i keep getting the error code: An object reference is required for the nonstatic field, method, or property 'ShutdownTimer.Form1.richTextBox1()' 

The following is the code ive used.

 

Form2  

*****

private void close_Click(object sender, EventArgs e)  

        {  

            Form1.update();  

            //this.Close();  

        }  

 

Form1 

***** 

public static void update()  

        {  

            richTextBox1.Text = "Updated" + "\r\n";  

        }  

 

I thought i got round the error code by using the following code.

Form2  

*****

private void close_Click(object sender, EventArgs e)  

        {  

            Form1.update();  

            //this.Close();  

        }  

 

Form1 

***** 

public static void update()  

        {  

Form1 fm = new Form1();  

            fm.richTextBox1.Text = "Updated" + "\r\n";  

            

        }  

 

So this compiles but “Updated” doesn’t appear in the richTextBox.

 

What have i done wrong?

 

Hope to hear a response soon,

 

Rob

 

·         EDIT: In the code above i added a button on to Form2 to call method asd. Even that wasnt able to put "qwerty" in to the richTextBox1. Let alone trying to call it from another method. I have made a new project now so i could figure this out. I dont want to mess around too much with the proper program. Thats why the method names have changed.

I now have the following code.

Form1  

*****  

public void button2_Click(object sender, EventArgs e)  

        {  

            Form2 fm = new Form2();  

            fm.asd();              

        }  

 

Form2  

*****  

public void asd()  

        {  

            i += 1;  

            MessageBox.Show("here " + i, "asd");  

            this.richTextBox1.Text += "qwerty " + i + "\r\n";  

        } 


From Form1 the method asd is called and i get the messageBox but "qwerty" isnt wrote in to richTextBox1. "i" is also updated every time i call it from Form1. If i click the button on Form2 that calls asd, it works perfectly. So what am i now missing out for the richTextBox1 to work properly? I have noticed other things to do with the objects on the form like buttons to not show and hide when the method is called from Form1.

Hope to hear a response soon

 


Answers (12)