about global variable

W

www.msale.net

I use c# of vs.net2003,and develop for ppc2002.
I need pass a variable value to several Forms,and the variable value is
from a Form.
I want to use global variable,e.g:extern.but I find it is difficult.
please help me,and thanks.

____________________________________________________________________________
http://www.msale.net/bbs
a Chinese-language message board for developers,including
palm,ppc,symbian,and etc.
 
P

Peter Foot [MVP]

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
 
B

Butt Chin Chuan

You can also try to declare public variables in a module
which will enable you to access it anywhere within your
application.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

about InputPanel 2
eVC VS vs.net 2
about vs.net2003 or above 5
how do I set tab order on the form 2
about c# and printer 1
global variable 3
Global variable seems missing 3
Pass Variable At Design Time 2

Top