如何将值从文本框传递到不同表单上的标签
本文关键字:表单 标签 文本 | 更新日期: 2023-09-27 18:25:38
我接到了一个制作井字游戏(尺寸8*8)的任务,到目前为止,我设法对主游戏进行了编码,但我在将玩家名称的值从新游戏表单传递到主表单时遇到了问题,有人能帮我吗?
主窗体的代码
public void NameValue1(TextBox NV1)
{
lblName1.Text = NV1.Text;
}
public void NameValue2(TextBox NV2)
{
lblName2.Text = NV2.Text;
}
private void mnuNewGame_Click(object sender, EventArgs e)
{
iFlag = 1; // This is used to run the paint function on the form
StartGame();
for (int i = 0; i < 64; i++)
{
this._btn[i].Click += new System.EventHandler(this.ClickControl);
this._btn[i].MouseMove += new MouseEventHandler(this.MoveControl); // DEBUG // these 2 allow me to check 'does my mouse hover on the right box?'
this._btn[i].MouseLeave += new System.EventHandler(this.LeaveControl); // DEBUG //
}
}
public void StartGame()
{
frmNewGame OpenForm = null;
OpenForm = new frmNewGame();
OpenForm.ShowDialog();
//lblName1.Text = "Player 1"; // PLACEHOLDER // these 2 are what I'm trying to replace to accept values from newgameform
//lblName2.Text = "Player 2"; // PLACEHOLDER //
lblName1.Visible = true;
lblName2.Visible = true;
Random RandomNumber = new Random();
int Start = RandomNumber.Next(0, 3);
if (Start == 1)
{
PlayerTurn = "Player1";
lblName1.Font = new Font("Microsoft Sans Serif", 17, FontStyle.Underline | FontStyle.Bold);
lblName2.Font = new Font("Microsoft Sans Serif", 17, FontStyle.Regular | FontStyle.Bold);
}
else if (Start == 2)
{
PlayerTurn = "Player2";
lblName1.Font = new Font("Microsoft Sans Serif", 17, FontStyle.Regular | FontStyle.Bold);
lblName2.Font = new Font("Microsoft Sans Serif", 17, FontStyle.Underline | FontStyle.Bold);
}
NumberTurn = 0;
for (int i = 0; i < 64; i++)
{
_btn[i].Text = "";
_btn[i].BackColor = Color.Yellow;
_btn[i].Visible = true;
_btn[i].Enabled = true;
}
}
新游戏形式的代码
public delegate void PassName1(TextBox tbxPlayerName1);
public delegate void PassName2(TextBox tbxPlayerName2);
private void btnOK_Click(object sender, EventArgs e)
{
frmConnectFour frmGame = new frmConnectFour();
PassName1 PN1 = new PassName1(frmGame.NameValue1);
PassName2 PN2 = new PassName2(frmGame.NameValue2);
this.DialogResult = DialogResult.OK;
}
正如你所看到的,我已经准备好了表单之间的连接来读取玩家名称文本框(没有错误),但我在如何将其传递给主表单上的startgame()函数方面遇到了问题
p.S:如果需要,我可以上传解决方案
这个话题已经讨论了数千次,但每次都有点不同
在这种情况下,您可以在newgameform
中创建两个公共属性
当用户单击"确定"按钮时,将使用newgameform
上的TextBoxes值设置属性
然后很容易从主表单中读取它们
public string Player1 {get; private set;}
public string Player2 {get; private set;}
private void btnOK_Click(object sender, EventArgs e)
{
this.Player1 = txtBoxForPlayer1.Text;
this.Player2 = txtBoxForPlayer2.Text;
this.DialogResult = DialogResult.OK;
}
并且以的主要形式
public void StartGame()
{
using(frmNewGame OpenForm = new frmNewGame())
{
if(DialogResult.OK == OpenForm.ShowDialog())
{
lblName1.Text = OpenForm.Player1;
lblName2.Text = OpenForm.Player2;
lblName1.Visible = true;
lblName2.Visible = true;
.....
}
}
}