orange
orange

Reputation: 341

Can't set the label on form

I have a Form with some private properties

namespace TestApplication
{
    public partial class ResultDialog : Form
    {
          String someText;

In a method, I have a method called SetupForm

 label1.Text = someText;

I get an error message and it says

Error 1 An object reference is required for the non-static field, method, or property TestApplication.ResultDialog.someText' X:\ResultDialog.cs 50 13 TestApplication

Upvotes: 0

Views: 164

Answers (4)

tsells
tsells

Reputation: 2771

Is the setup form method being called before the Initialize Method in the constructor? If so the label doesn't exist yet.

Upvotes: 0

JeremyK
JeremyK

Reputation: 1103

Is label1 or SetupForm static? if so your string needs to be static as well.

Static functions can only alter static values. If the function is static, it wont know what label1 is as its part of an instance of that class.

Bad:

class SomeClass
{
     string m_value = 0;

     static setValue(int value)
     {
          m_value = value;
     }
}

Good:

class SomeClass
{
     static string m_value = 0;

     static setValue(int value)
     {
       m_value = value;
     }
}

What you probably need:

static void SetupForm(Label label, string value)
{
    label.Text = value;
}

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176896

is the code in same file try out

 this.label1.Text = this.someText;

Must sure that you are not setting value in static function

Upvotes: 1

Praveen
Praveen

Reputation: 1449

As per my understanding, your method "SetupForm" might be a static method and that might be the primary reason behind getting this error.

Upvotes: 0

Related Questions