I am trying to pass a string from Form2.cs to Form1.cs and then display it in a message box. For some reason, the variable in the string is not showing but the rest of the text is.
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;
}
}
this might work .. u need to call the function somewhere to make it work.
I fixed it by calling it in the label click; so u need to click the label to update the value in the other form.
u can add this function to events like a timer event which ensures that it's always updated within a perfect time.
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;
}
}
You can create a property in Form1 to hold the player name, and then in Form2, when the input of player name changed, you will update the property of Form1. See the code:
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.