使用按钮在表单之间传递变量

我想知道如何从form1到form2传递,比如说一个整数。

我尝试通过一个打开form2的按钮来做到这一点,但是事件按钮点击无法识别整数…我该怎么办?

在form1中我有整数x,我希望当我点击button1时,form2会在标签中打开x值。

如果有一种方法可以在没有按钮的情况下传递信息(那时我可以使用按钮来打开form2),这也很棒。

你可以使用第二种forms的构造函数。

private int input; public Form2(int input) { this.input = input; InitializeComponent(); } 

在创建对象时,可以传递var(int in here):

  int myvar=911; Form2 tmp = new Form2(myvar); tmp.Show(); 

现在你可以在form2中使用那个私有变量:

 lbl.Text=input.toString(); 

在Form1中:

 private void button1_Click(object sender, EventArgs e) { Form2 tmp = new Form2(911); tmp.Show(); } 

在Form2中:

  public Form2(int input) { InitializeComponent(); label1.Text = input.ToString(); } 

发送你的代码来解决这个问题。我找不到为什么它没有你的代码不识别你的vars!

在您的代码中,两个表单都可以访问变量。 例如,创建一个新的Namespace并添加一个public static class FormData其中包含一个public static int Value

 namespace GlobalVariables { public static class FormData { public static int Value { get; set; } } } 

然后,从两个表单中,您可以使用GlobalVariables.FormData.Value访问所述变量(并对其进行修改)。 在这里,我把它作为一个属性,但你可以做任何你想要的任何东西。

或者通过Form2构造函数传递值,您可以创建一个设置标签值的属性,例如

窗体2

 public partial class Form2 : Form { public Form2() { InitializeComponent(); } public int XValue{ set{ label1.Text = value.ToString(); } } } 

Form1中

  public partial class Form1 : Form { private int x = 10; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 form2 = new Form2(); form2.XValue = x; form2.Show(); } }