How to make a variable that will work on multiple forms?

14,311

Solution 1

In your first form you should have (Assuming you're using the designer)

//Form1.cs
namespace myProject
{
    public partial class Form1 : Form
    {
        public static int myInt = 50;
        public Form1()
        {
            InitializeComponent();
        }
    }
}

To access in your second form, assuming they are in the same namespace, use:

//Form2.cs
namespace myProject
{
    public partial class Form2 : Form
    {
        int thisInt;
        public Form2()
        {
            InitializeComponent();
            thisInt = Form1.myInt;
        }
    }

Solution 2

Don't create any static or public variable like that... You should create a property in second form that you can access from first form. though you can transfer your value directly in your second form without declaring any static variable.

//Form2

private string value1 = string.Empty;
public string Value1
{
   get { return value1; }
   set { value1 = value; }
}


//Form1

private void YourMethod()
{
    Form2 frm = new Form2();
    frm.Value1 = "This is a sample value to pass in form 2";
    frm.Show();

}

Now, you can get value in Form2 by using Value property.

//Form2
private void Form2_Load(object sender, EventArgs e)
{
     string myValue = Value1; //here you can use value like that
}

Solution 3

You can change the constructor for form 2 to accept the variable and pass it from form 1.

public Form2(int passed)

If you want to pass it by reference then.

public Form2(ref int passed)

To open Form 2 with the variable by reference.

int passed = 1;
new Form2(ref passed);

If passed by reference, if the value is changed in form 2 that change will also show up in form 1 because "is the same" variable (same value in memory).

Share:
14,311
James
Author by

James

Updated on June 05, 2022

Comments

  • James
    James almost 2 years

    Right now I have 2 forms. I would like to make a variable (Like a int) that will pass between the 2 forms. For instance, I make a variable on the first form with the code: public static int myInt = 50; But how to I transfer that variable to form 2?