Accesing variables of other forms
I'm am just learning how to work with c# .net. Now i have a trouble in accessing a varible in form1 from form2. Can any one tell me how to do it?
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.

AlanRank #669 · 3.6K reputationPosted Feb 25, 2008, 12:55 AM EST
Well, to start with you need a reference to form1.
If you're using .NET 2.0 or later, you can get a reference to an open form whose class name is Form1 with this line:
Form1 f1 = (Form1)Application.OpenForms["Form1"];
To access a variable on Form1 from another form or class, that variable needs to be either public or internal. Form variables such as controls are normally private so you need to change the accessibility before you do anything else. For controls you can do it from the Properties Box in the VS designer.
So, suppose textBox1 is a public variable on Form1 and you want to change its Text property from Form2. You can then do it with the line:
f1.textBox1.Text = "whatever";