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?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Feb 25, 2008, 5:55 AM
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";