问题
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