2

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?

Shell
  • 6,818
  • 11
  • 39
  • 70
James
  • 213
  • 1
  • 3
  • 13

3 Answers3

6

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
}
Shell
  • 6,818
  • 11
  • 39
  • 70
3

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;
        }
    }
Shadow
  • 3,926
  • 5
  • 20
  • 41
  • I am a newbie to C#. How do I get them into the same namespace? – James Jun 21 '14 at 02:02
  • They should automatically be in the same namespace. When you make a project the namespace has the same name as the project, and generally every form is put into it (tested just to make sure, works fine for me) – Shadow Jun 21 '14 at 02:07
  • Okay, So I just tried the code and it gave me an error on form 2. It says "Form 1 does not contain definition for myInt" – James Jun 21 '14 at 02:11
  • It turns out I had the code in the wrong place! Works now! Thank you so much! – James Jun 21 '14 at 02:30
2

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).

KRose
  • 74
  • 3