从另一个表单访问控件值

时间:2012-12-22 04:35:39

标签: c# forms controls label

我做了一个简单的抽动,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
  ...

2 个答案:

答案 0 :(得分:2)

首先将标签lblDraw设置为

frmStats格式

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

<强> 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
        frmStats frm = new frmStats();
        string number = frm.strNumber;
        frm.strNumber = (Convert.ToInt32(number) + 1).ToString(); //incrementing by 1
    }

或者只是将标签lblDraw修饰符设置为公开,这是不推荐的。

答案 1 :(得分: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();
    }
相关问题