You cant have Global variables however if you make a public property on your
main form you will be able to access the variable from other forms as long
as you have a reference to it. The easiest way is to modify your form
constructors to take a parent form argument e.g.
//this is your main class which has the variable you want to expose
public class MyMainForm : System.Windows.Form
{
//existing form members
private string examplevariable;
//existing form code
//example method showing creating a child form
public void OpenChildForm()
{
//create child form passing this instance in as an argument
MyChildForm newchild = new MyChildForm(this);
//show child form
newchild.Show();
}
//exposes your variable publically
public string ExampleProperty
{
get
{
return examplevariable;
}
}
}
//this is a child class you want to create and show at some point in your
application, and be able to access a variable from the parent form
public class MyChildForm : System.Windows.Form
{
//existing form members
private MyMainForm parentreference;
//constructor
public MyChildForm(MyMainForm parent)
{
parentreference = parent;
}
//existing code
public void DoSomething()
{
//using variable from parent form
somevalue = parentreference.ExampleProperty;
}
}
From your child form you can access any of the public properties (or
methods) of the parent because you have assigned a reference to it when the
child was created. Note that although you could mark the variable public in
the parent to access it directly it is better to write a property around it
so that you can add validation etc - in the example above the
ExampleProperty is read-only.
Peter
--
Peter Foot
Windows Embedded MVP
In The Hand
http://www.inthehand.com