将变量值从Form1传输到Form2

-5 c# winforms

我一直很难将我的变量值从表单1传输到我的form2.问题是我想在Form2加载时在Form2 textBoxes中显示我在Form1中初始化的结果(当我单击相应的按钮时,它会显示一个ShowDialog()).

我的问题是结果不在我的Form2中传输,给我的所有变量一个0值.

这是我在表格中的内容:

//Variables in my Form 1

public partial class Form1 : Form
{
   public static double VAR_1 = 1;
   public static double VAR_2 = 2;
   public static double VAR_3 = 3;

   //Here I put all my textBoxes and other methods of the class
}

//Variables in my Form 2

public partial class Form2 : Form
{
    private void Form2_Load(object sender, EventArgs e)
    {
         this.textBox1.Text = Form1.VAR_1.ToString();
         this.textBox2.Text = Form1.VAR_2.ToString();
         this.textBox3.Text = Form1.VAR_3.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

Lua*_*aan 6

您根本不需要使用"全局变量".只需创建一个方法(或属性),Form2它接受您想要使用的参数,并在调用之前调用它ShowDialog,例如:

var form2 = new Form2();
form2.SetData(text1, text2, text3);
form2.ShowDialog();
Run Code Online (Sandbox Code Playgroud)

您甚至可以将这些参数添加到构造函数中,或者使用您自己的静态方法来显示表单.有很多方法不涉及回归到老式程序编程:)