-5

我做了一个简单的tic,tac,toe游戏。我有两种形式,Form1frmStats。在我的frmStats我有一个标签lblDraw。我想要它,所以当玩家打成平局时,标签会加一。如何从Form1的代码中访问它?

我的 Form1 代码:

if (winner != 0)
  this.Text = String.Format("Player {0} Wins!", winner);
else if (winner == 0 && turnCounter == 9)
  this.Text = "Draw!";
 //this is where i want/think the code should be to change the label
else
  ...
4

2 回答 2

2

首先将标签设置lblDraw

frmStats形式上_

 public string strNumber
 {
    get
    {
        return lblDraw.Text;
    }
    set
    {
        lblDraw.Text = value;
    }
 }

表格1

    if (winner != 0)
        this.Text = String.Format("Player {0} Wins!", winner);
    else if (winner == 0 && turnCounter == 9)
    {
        this.Text = "Draw!";
        //this is where i want/think the code should be to change the label
        frmStats frm = new frmStats();
        string number = frm.strNumber;
        frm.strNumber = (Convert.ToInt32(number) + 1).ToString(); //incrementing by 1
    }

或者简单地将 LabellblDraw修饰符设置为public,这是不推荐的。

于 2012-12-22T04:45:22.290 回答
0

虽然 Mr_Green 的回答有效,但我认为正确的方法是在打开 Form1 时将其作为变量传递给 frmStats:

frmStats newForm = new frmStats(this);

在 Form1 中创建一个属性来访问数字:

    public int Num
    {
        get
        {
            return myNumber;
        }
    }

然后在 frmStats 构造函数中,您可以访问父表单的公共属性:

    public frmStats(Form1 form)
    {
        InitializeComponent();

        lblDraw.Text = form.Num.ToString();
    }
于 2012-12-22T04:59:33.207 回答