2
Answers

How to define global variable in C#

Hi all,

Please help me solving following query:

How to add global variable in C# window base application. This variable must be accessible to all forms.

What I exactly want is:

I have a variable "UserName" and "UserType". When user click "Submit" button on Login form, user name get stored in variable "UserName" and user type get stored in variable "UserType". After click "Submit" button Login form get closed and "Project" form get open.

On "Project" form there are label "User Name" and "User Type". When "Project" form get open, the value of "UserName" and "UserType" variable should be get displayed in front of these labels.

I hope you understand my question.

Thanks and regards,

Swapnil.
Answers (2)
0
Dipen Lama
NA 331 195.9k 18y
One way to do is create a class called "Users" and have two static variable on it "UserName" and "UserType". Now once you store the variable in this class static variable you can get the value of it from any form.

Let me know if this solve your problem.
0
Dale
NA 15 0 18y
Im new to programming so this might not be right.

but i believe you dont want to create a global variable.

you want to define a method in the same class as your original form that returns The username and one that returns the usertype. 
  implement them somewhere between the constructor and destructor.   Then call it from the second form with a reference to the original class and method.

This is something i am going to try in the near future so im not sure on all of the specifics.  like i said i am new to this, but good luck and let me know if it helps, as i will be trying to do the same thing soon.