how do I access form1 string variable from a different class?
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
}
public string deva = "123";
//button
private void button8_Click(object sender, EventArgs e)
{
deva = "456";
}
private void button9_Click(object sender, EventArgs e)
{
Other ks = new Other();
ks.test_me();
}
}
public class Other: Form1
{
//trying to access Form1 variable.
public void test_me()
{
Form1 fm = new Form1();
MessageBox.Show(fm.deva);
//deva is 123 but not 456.
//I clicked on button and values changes it form1 however from here it assigns just default value
}
//
//Does creating a new form1 will reset its values?
//Somebody please help me. how to solve this issue.
}
default value is set a every new instance if you want to keep last value you make a
static
propertyAnswer on the title question.
Read Jon Skeet's comment for explanation of reason why your approach not workiing.
If you want have access to the variables of another instance, then you need in someway have reference to that instance
One way pass it in the constructor of
Other
Then where you create new instance of
Other
pass instance of yourForm1
ti the constructor ofOther
no need to inherit from form1, please pass the object via constructor
Make your variable deva Static. Access it with Class directly not object.