我发现将 int 和字符串值从一个传递到下一个的最简单方法是:
private void gameStart_Click(object sender, EventArgs e)
{
string machineName = System.Environment.MachineName;
int numberOfPlayers = 10;
multiplayerGame y = new multiplayerGame(numberOfPlayers, machineName);// multiplayerGame is the next form, and y is just a very simple variable the new form plus variables that are being passed is assigned to
this.Hide();();// hides this (current) form
y.ShowDialog();//here is where the variable y is used with .ShowDialog to make your program open the new form
}
}
上面的代码是我的一个程序中的一个示例,也是我在表单中使用的代码,传递了我想在下一个表单中使用的变量。在下一个表单中,您需要添加以下代码才能看到变量并将其分配给整个表单的可用变量。
public partial class multiplayerGame : Form
{
private int numPlayers;// This is the variable that will be used on this form for the int variable being passed
private string myPcName; ;// This is the variable that will be used on this form for the string variable being passed
}
在接下来的部分中,您的程序将初始化您需要的所有内容,以允许 form1 中的变量传递到新表单中,并将其分配给为新表单创建的变量。在我的示例中,这是多人游戏。
public multiplayerGame(int numberOfPlayers, string machineName)// int so the new form knows your passing an int, then the name of your variable same goes for the string variable
{
this.myPcName = machineName;// here you assign the private string created above for this form to equal the string variable being passed into this from form the previous form
this.numPlayers = numberOfPlayers; // here you assign the private int created above for this form to equal the int variable being passed into this from form the previous form
InitializeComponent();
}
然后,您将拥有一个可以使用的变量,该变量将被识别,并且在您加载第二个表单时已经具有从前一个表单设置的值。在这一点上唯一剩下的就是在需要的地方使用你的变量。