Theodore Theodore - 1 year ago 74
C# Question

how to store in a global variable c#

Hello guys how do I store the

voterid
into a global variable so I can use it on another form? I will use this
voterid
in order to check if the voter has already voted.

{
MessageBox.Show("Welcome!");
OleDbCommand comd1 = new OleDbCommand();
comd1.Connection = connection;
comd1.CommandText = "SELECT VoterID FROM tbl_voter where Uname='" + txt_user.Text + "' and Pword='" + txt_pass.Text + "'";
voterid = Convert.ToString(comd1.ExecuteScalar());
MessageBox.Show(voterid);

connection.Close();
connection.Dispose();

this.Hide();
vote form3 = new vote();
form3.ShowDialog();

}

Answer Source

If we are talking about a Windows Forms application, and by "global" you mean "common across the process," then you can use a static variable.

In this example i create a special class just to hold static variables, and declare one field and one property that will be available to your program and will hold one and only one value across the entire process.

static class GlobalVariables
{
    static public string SomeVariable { get; set ; }  //As a property
    static public string SomeOtherVariable;           //As a field
}

Note that if your program is multi-threaded, it may be a good idea to put a critical section around static variables, like this:

static class GlobalVariables
{
    static private string LockObject = new Object();
    static private string _someVariable;

    static public string SomeVariable 
    { 
        get
        {
            lock(LockObject) { return _someVariable; }
        }
        set
        {
            lock(LockObject) { _someVariable = value; }
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download