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.

Recommended Answers

All 22 Replies

I don't know how to solve your problem, but I'm guessing there's no such thing as a global variable since that would destroy encapsulation.

As a guess, couldn't you use static members of a class (called sessionSetttings or similar) and then have a property access function (is that what they're called?) to modify it.

Is this an accepted way of doing things in C#? If not, I would be very interested in the actual method too.

Thanks.

In this problem I am speaking about Window based application and not Web based application. Here global variable means the variable which is accessible to all forms or classes.

I tried static member, I define static variable "UserName" in seperate class (GlobalClass). When user inserts user name and password in LoginForm and clicks "Submit" button the user name gets stored in static variable ("UserName") and LoginForm closes, here is the problem, when LoginForm get closed the value of static variable "UserName" is also wiped out. I want "UserName" on "ProjectForm" which get open after LoginForm closes.

I hope you got it.

Thanks and regards,

Swapnil.

I get what you mean.

Make sure the constuctor is a static constructor too, this way it will only happen the first time you construct the class.

You're looking at an issue of object persistence, more than likely.

When you close the form, the object that the form represents, including all members included in it, are disposed. More than likely, you'll want to serialize the information in a temp file, or something like that.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/objserializ.asp

That'd be my guess. I'd really like to know if there's something better.

Thanks Alex,

I tried "Serialzation" and it is working fine. But problem is that whenever you want to retrive the value of variable you have to "deserialize" the object.

In my case, there is variable "UserName". When user insert UserName adn password and clicks "Submit" button, user name gets stored in "UserName" variable and Login form closes. Now what I want is, "UserName" should get displayed on each and every form which I will open. And there are around 10 to 12 forms.

I hope you got it.

Thanks and regards,

Swapnil.

Easy. this should work, you just need a static class:

Add a new class.cs file to the project and stick something like this in it.

static class GlobalClass
    {
        private string m_globalVar = "";

        public static string GlobalVar
        {
            get { return m_globalVar; }
            set { m_globalVar = value; }
        }


    }

Use it anywhere like this (it's static you don't instantiate it anywhere)

GlobalClass.GlobalVar = "Some value";

retrieve it anywhere like this:

myFormLabel.Text = GlobalClass.GlobalVar;
commented: worked well +0

Thanks hollystyles,

This is what I am looking for. Thanks very much.

Static class contains only static Members.

Hence in your code, "m_globalVar" should also be define as static. Otherwise it will give error.

static class GlobalClass
{
    private [U]static[/U] string m_globalVar = "";

    public static string GlobalVar
    {
        get { return m_globalVar; }
        set { m_globalVar = value; }
    }


}

If possible can you tell me how to encrypt the password.

I want both encrypt and decrypt methos.

Thanks and regards,

Swapnil.

Hence in your code, "m_globalVar" should also be define as static. Otherwise it will give error.

Absolutely right , typo on my part tut tut.

Encryption thpt no idea not something I've really ever done i'm afraid.

Thanks a lot for your info! Worked For me!

worked for me aswell but, why does it need to be static? If it wasn't static could we create new instances of a globalVar and hense store multiple variables? I shall be attempting this

....I attempted it and failed .. any1 know of a way to do this on a multiple scale? Obviously w/o having to create a whole class several times.

efficacious,

You could just add a static List to a class. For example:

public class Global
{
	//instance variables

	static List<Global> CLASSES = new List<Global>();
	public static Global this[int n]
	{
		get { return CLASSES[n]; }
	}
	public Global()
	{
		CLASSES.Add(this);
	}
}

i'm still kinda a noob at C# can u show how i can use that class to make new global variables..ty

i'm still kinda a noob at C# can u show how i can use that class to make new global variables..ty

Take a look at this:

using System;
using System.Collections.Generic;

public class Global
{
    private static readonly List<Global> CLASSES = new List<Global>();
    public static int Count
    { get { return CLASSES.Count; } }
    public static Global Get(int index)
    { return CLASSES[index]; }

    public int value;

    public Global()
    { CLASSES.Add(this); }
}

public static class Test
{
    static void Main()
    {
        new Global();
        Global.Get(0).value = 1;
        Console.WriteLine(Global.Get(0).value);
        Console.ReadKey();
    }
}

It's not a very sophisticated example, but hopefully you can learn from it. If you have any more questions, you can feel free to PM me.

can use session variables...

Hi Guys
When using a static class, does all its attributes and methods need to be static aswell??
thanks in advance

worked well. thanks for this info. i'm new in c# and using windows forms because i'm using PB (for win forms) and ASP.Net and VB.net (for web projects). ;-)

again thanks a lot...

i have an idea but its work with VB
look man you will add a module
1-right click on your project
2- add
3- new item
4- module
at the module body you could define whatever you want like....
Module Module1
public ahmed As string
Public x As Integer
Public y As Integer
Public z As Integer = 59
End Module

and you will find those variable at any form you have

plz if any one know what is the module at c# items tell me
thats 100% work at VB
thanx alot

dude you need to declare the global variable in program.cs
it would help you to access such variable in every form.
try this out if it wont works i will show you an example by retrieving username and usertype which is your need

Hello HollyStyles,
Great Post!!!
But in order to work error free, it requires two small modifications. First, in your code, "m_globalVar" should also be define as static. Otherwise it will give error. Moreover, class should be defined Public, otherwise, it can't be accesssed.

public static class GlobalClass
{
private static string m_globalVar = "";
public static string GlobalVar
{
get
{
return m_globalVar;
}
set
{
m_globalVar = value;
}
}
}

Regards
Geet


Easy. this should work, you just need a static class:

Add a new class.cs file to the project and stick something like this in it.

static class GlobalClass
    {
        private string m_globalVar = "";

        public static string GlobalVar
        {
            get { return m_globalVar; }
            set { m_globalVar = value; }
        }


    }

Use it anywhere like this (it's static you don't instantiate it anywhere)

GlobalClass.GlobalVar = "Some value";

retrieve it anywhere like this:

myFormLabel.Text = GlobalClass.GlobalVar;

Welcome.

I'm glad you got it helpful. If you want to ask question, start your own thread.

Thread Closed.

Hello. i have a only problem in the code.
My Code GlobalClass.cs
`

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReservaLab
{
    class GlobalClass
    {
        private int m_globalType;

        public static int GlobalType
        {
            get { return **m_globalType**; }
            set { **m_globalType** = value; }
        }

        private string m_globalName = "";

        public static string GlobalName
        {
            get { return **m_globalName**; }
            set { **m_globalName** = value; }
        }
    }
}

`
And the VisualStudio generate the next error.

Error 1 An object reference is required for the non-static field, method, or property 'ReservaLab.GlobalClass.m_globalType' at Line 14.

Error 2 An object reference is required for the non-static field, method, or property 'ReservaLab.GlobalClass.m_globalType' at Line 15.

Error 3 An object reference is required for the non-static field, method, or property 'ReservaLab.GlobalClass.m_globalName' at Line 22.

Error 4 An object reference is required for the non-static field, method, or property 'ReservaLab.GlobalClass.m_globalName' at line 23.

I don't understand what mean this errors.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.