简体   繁体   中英

Accessing controls on a Windows Form C#

I'm having some trouble doing a very simple task. I have a rich textbox on my Windows form and I'm trying to access it outside of any button clicks. I've realized that the control is not "public" and I can't just call it in the code where ever I want to change it.

The error I'm getting is: An object reference is required for the non-static field, method, or property. I know it's a really novice question but I've tried a lot of way to solve this and I cant figure it out. Can someone please help?

The code is

public static void SeeIfFinished()
{
   if (FinishedThreadCount == 1)
   {
      richTextBox1.Text = "text";
   }
}

Your method is static - remove the static modifier, and call it by referring to a specific instance of the form:

myForm.SeeIfFinished();

or if your calling code is inside the form class, just:

SeeIfFinished();

You can't access an instantiated object inside a static method.

Put the code in a method not marked with the static keyword.

A static method can only see static members of its class and whatever is passed in as a parameter. richTextBox1 is not a static member of your window class, so it cannot be referenced inside a static method.

Add a parameter to your static method (RichTextBox richTextBox) . When you call the static window method, pass in a richTextBox1 and it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM