在C#中从一个表单传递到另一个表单时字符串不可读

时间:2015-12-04 03:12:10

标签: c# string winforms

我正在尝试将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;
        }
    }

2 个答案:

答案 0 :(得分:0)

这可能有用..你需要在某个地方调用函数才能使它工作。

我通过在标签点击中调用它来修复它; 所以你需要点击标签来更新另一种形式的值。

你可以将这个功能添加到像定时器事件这样的事件中,以确保它在一个完美的时间内始终更新。

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;
    }

}

答案 1 :(得分:0)

您可以在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();
    }
}