简体   繁体   中英

Transferring variable values from Form1 to Form2

I've been having a hard time transferring my variable values from my form 1 to my form2. The thing is I want to show the results I initialized in my Form1, in Form2 textBoxes as soon as the Form 2 loads (Which appears with aa ShowDialog() when I click the appropriate button).

My problem is the results don't transfer in my Form2, giving all my variables a 0 value.

Here's what I put in my Forms:

//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();
    }
}

You don't need to use "global variables" at all. Just create a method (or property) on Form2 that takes the parameters you want to use, and call that before calling ShowDialog , eg:

var form2 = new Form2();
form2.SetData(text1, text2, text3);
form2.ShowDialog();

You could even add those parameters to the constructor, or make your own static method to show the form instead. There's a lot of ways that don't involve regression to old-school procedural programming :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM