如何显示来自其他表单的数据

时间:2010-05-22 16:47:48

标签: c# winforms

这基本上是一个tic tac toe游戏,当玩家获胜时,我有另一个名为Winner.cs的形式我希望它调用表单(这部分有效)然后我想要它说xWinner.label = b1。文字“”+赢得了比赛!我无法工作的部分是在获奖者表单标签中显示文本。有一个消息框的示例已注释掉以供参考 而不是b1.text

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyGame
{
    public class Result1
    {


        static private int[,] Winners = new int[,]
                   {
                        {0,1,2},
                        {3,4,5},
                        {6,7,8},
                        {0,3,6},
                        {1,4,7},
                        {2,5,8},
                        {0,4,8},
                        {2,4,6},
                   };
        static public bool CheckWinner(Button[] myControls)
        {
            bool gameOver = false;
            for (int i = 0; i < 8; i++)
            {
                int a = Winners[i, 0], b = Winners[i, 1], c = Winners[i, 2];
                Button b1 = myControls[a], b2 = myControls[b], b3 = myControls[c];
                if (b1.Text == "" || b2.Text == "" || b3.Text == "")
                    continue;
                if (b1.Text == b2.Text && b2.Text == b3.Text)
                {
                    b1.BackColor = b2.BackColor = b3.BackColor = System.Drawing.Color.LightCoral;
                    b1.Font = b2.Font = b3.Font = new System.Drawing.Font("Microsoft Sans Serif", 32F, System.Drawing.FontStyle.Italic & System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
                    gameOver = true;
                    Form xWinnerForm = new xWinnerForm();
                    xWinnerForm.Show();

                    //MessageBox.Show(b1.Text + " .... Wins the game!", "Game End", MessageBoxButtons.OK);
                    //break;
                }
            }
            return gameOver;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您可以做的一件事是在cWinnerForm类中创建自己的Show方法:

public void Show(string text)
{
    this.myLabel.Text = text;
    this.Show();
}

然后你必须在代码块中更改两行代码:

来自:

Form xWinnerForm = new xWinnerForm();
xWinnerForm.Show();

到此:

xWinnerForm xWinnerForm = new xWinnerForm();
xWinnerForm.Show(b1.Text);

另一种选择是将文本传递给xWinnerForm的构造函数。

答案 1 :(得分:0)

听起来像b1的文本框是私有的(或受保护的)。将其公之于众应该可行。

如果您想从b1获得的唯一内容是获胜者的名字,则winforms中的每个表单都有一个标签,该标签是公开的。你可以在有人赢得胜利者的名字之后设置标签,然后在另一个表格中设置b1.Tag.ToString()来获得它。

另外,作为旁白;在“现实生活”应用程序中,您可能希望将其中一些组件封装到不同的类中,而不是让表单查看彼此的控件。

修改

我现在面前没有Visual Studio,但我相信在属性窗口中您可以将该特定文本框设置为“public”。