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?
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
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With