从另一个窗体访问控件值

本文关键字:控件 访问 窗体 另一个 | 更新日期: 2023-09-27 17:49:27

我制作了一个简单的tic,tac,toe游戏。我有两种形式,Form1frmStats。在我的frmStats上我有一个标签lblDraw。我希望当玩家打成平局时,标签会增加1。我如何从Form1的代码访问?

my Form1 code:

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
  ...

从另一个窗体访问控件值

首先将标签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
    }

或者直接将Label lblDraw修饰符设置为public,不建议这样做。

而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();
    }