Global Variable In C#

In web applications, you can make a variable global by using the app state of the application. You can also declare variable in a session for the session level. But in a WinForms application, you can't use app or session states. However, you can make a global variable by creating a static class in a separate class file in your application.
 
First, create a class called global in your application with the code given below. The class also has a static variable. 
  1. class Global  
  2.     {  
  3.         public static string UserID;  
  4.          
  5.     }  
Now, you can access it from anywhere in your forms after assigning a value to it.
  1. Global.UserID = comboBox1.Text.ToString();  
You can use it in any form, as shown below.
  1. if(Global.UserID == "abdulateef")  
  2.             {  
  3.                 dataGridView1.Refresh();  
  4.             string ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver};Server=localhost;Database="";User Id="";Password=";  
  5.             string query = "Select filename, encfile, password,date,username FROM encinfor";  
  6.             OdbcConnection conn = new OdbcConnection(ConnectionString);  
  7.             conn.Open();  
  8.             try  
  9.             {  
  10.                 //populating the gridview1 on form load  
  11.                 DataSet ds = new DataSet();  
  12.                 using(OdbcDataAdapter adapater = new OdbcDataAdapter(query, conn))  
  13.                 {  
  14.                     adapater.Fill(ds);  
  15.                     dataGridView1.DataSource = ds.Tables[0];  
  16.                 }  
  17.             }  
  18.             catch(Exception ex)  
  19.             {  
  20.                 MessageBox.Show(ex.Message);  
  21.             }      
The best practice is to make sure that you don't assign different value to the same global variable. You can have many global variables, as per your desire. For an example, check the code given below.
  1. class Global  
  2.     {  
  3.         public static string UserID;  
  4.         public static string Status;  
  5.         public static string Adim;  
  6.   
  7.     }  
Thanks, I hope it helps.
 
C# now supports static classes. Learn more here:  Static Class In C#