Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

c# - An object reference is required for the non-static field, method, or property?

I know this is probably a very newbish question, so I apologize.

I am trying to access the Text property of a label on Form1 from another form, MaxScore.

When I click the Ok button on MaxScore, I want to set Form1's myGameCountLbl.Text to Form1's variable, max by using max.ToString().

Here is my code in the OK button event of MaxScore:

private void okBtn_Click(object sender, EventArgs e)
{
    Form1.myGameCountLbl.Text = Form1.max.ToString();
    Form1.compGameCountLbl.Text = Form1.max.ToString();
}

But when I go to compile it, I get the error:

An object reference is required for the non-static field, method, or property 'Towergame_2.Form1.myGameCountLbl'

I get the same error for Towergame_2.Form1.max and Towergame_2.Form1.compGameCountLbl.

Not quite sure how to fix this. Max is a public variable and the two labels are pubic as well.

Thanks!

This is the code in my constructor (thank you lassevk for the code!):

public Form1()
{
    //initialize vars
    myHp = 100;
    compHp = 100;
    youWon = 0;
    compWon = 0;
    money = 100;
    canCompAttack = true;
    gameOver = false;

    //show HowToPlay Dialogue
    HowToPlay howToPlay = new HowToPlay();
    howToPlay.ShowDialog();

    using (MaxScore maxScore = new MaxScore())
    {
        maxScore.MainForm = this;
        maxScore.ShowDialog();
    }

    InitializeComponent();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is by any chance Form1 the name of the class?

You need to have a reference to an instance of the form class.

Since okBtn is not on the same form, you need to give the MaxScore form a reference to the Form1 instance.

For instance, you can add this to your MaxScore form:

public Form1 MainForm { get; set; }

And then in your okBtn_Click method, you'll write this:

private void okBtn_Click(object sender, EventArgs e)
{
    MainForm.myGameCountLbl.Text = MainForm.max.ToString();
    MainForm.compGameCountLbl.Text = MainForm.max.ToString();
}

and then when you're constructing MaxScore from Form1 (I'm assuming that's what you're doing):

using (MaxScore scoreForm = new MaxScore())
{
    scoreForm.MainForm = this;
    scoreForm.ShowDialog();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...