在C#中从一个窗体传递到另一个窗体时,字符串不可读
本文关键字:窗体 另一个 字符串 一个 | 更新日期: 2023-09-27 18:25:32
我正试图将一个字符串从Form2.cs传递到Form1.cs,然后将其显示在消息框中。由于某种原因,字符串中的变量没有显示,但文本的其余部分显示。
Form1.cs
Form2 otherForm = new Form2();
public void getOtherTextBox()
{
otherForm.TextBox1.Text = player1;
}
private void labelClick(object sender, EventArgs e)
{
Label clickedLabel = (Label)sender;
if (clickedLabel.BackColor != Color.Transparent)
{
return;
}
clickedLabel.BackColor = isBlackTurn ? Color.Black : Color.White;
isBlackTurn = !isBlackTurn;
Color? winner = WinCheck.CheckWinner(board);
if (winner == Color.Black)
{
MessageBox.Show( player1 + " is the winner!");
}
else if (winner == Color.White)
{
MessageBox.Show("White is the winner!");
}
else
{
return;
}
Form2.cs
public TextBox TextBox1
{
get
{
return textBox1;
}
}
这可能有效。。你需要在某个地方调用函数才能使其工作。
我通过在标签点击中调用它来修复它;所以你需要点击标签以更新其他形式的值。
u可以将此函数添加到计时器事件之类的事件中,以确保它总是在完美的时间内更新。
public void getOtherTextBox()
{
otherForm.TextBox1.Text = player1;
}
private void labelClick(object sender, EventArgs e)
{
Label clickedLabel = (Label)sender;
getOtherTextBox();
if (clickedLabel.BackColor != Color.Transparent)
{
return;
}
clickedLabel.BackColor = isBlackTurn ? Color.Black : Color.White;
isBlackTurn = !isBlackTurn;
Color? winner = WinCheck.CheckWinner(board);
if (winner == Color.Black)
{
MessageBox.Show( player1 + " is the winner!");
}
else if (winner == Color.White)
{
MessageBox.Show("White is the winner!");
}
else
{
return;
}
}
您可以在Form1中创建一个属性来保存玩家名称,然后在Form2中,当玩家名称的输入发生变化时,您将更新Form1的属性。查看代码:
public class Form1()
{
//Code
private string PlayerName { get; set; }
private void labelClick(object sender, EventArgs e)
{
Label clickedLabel = (Label)sender;
if (clickedLabel.BackColor != Color.Transparent)
return;
clickedLabel.BackColor = isBlackTurn ? Color.Black : Color.White;
isBlackTurn = !isBlackTurn;
Color? winner = WinCheck.CheckWinner(board);
if (winner == Color.Black)
MessageBox.Show(this._playerName + " is the winner!");
else if (winner == Color.White)
MessageBox.Show("White is the winner!");
}
//More code
}
public class Form2()
{
private Form1 _frm;
public Form2()
{
this._frm = new Form1();
}
public void ShowFormWinner()
{
_frm.PlayerName = textBox1.Text;
_frm.Show();
}
public void OnPlayerNameChanged(object sender, EventArgs e)
{
_frm.PlayerName = textBox1.Text;
_frm.Show();
}
}