Accessing a controls value from another form [closed]

牧云@^-^@ 提交于 2019-12-13 11:29:28

问题


I made a simple tic,tac,toe game. I have two forms, Form1 and frmStats. on my frmStats I have a Label lblDraw. I want it so when the players get in a draw, the label will increment by one. How do I access that from Form1's code?

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

回答1:


First of all set the Label lblDraw as

In frmStats form

 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
    }

or else simply set the Label lblDraw modifier as public, which is not recommended.




回答2:


While Mr_Green's answer works I think the corrent way to do it would be to pass your Form1 as a variable to frmStats when you open it:

frmStats newForm = new frmStats(this);

Create a property within Form1 to access the number:

    public int Num
    {
        get
        {
            return myNumber;
        }
    }

Then in frmStats constructor you'd have access to the parent form's public properties:

    public frmStats(Form1 form)
    {
        InitializeComponent();

        lblDraw.Text = form.Num.ToString();
    }


来源:https://stackoverflow.com/questions/14000090/accessing-a-controls-value-from-another-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!