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.
- class Global
- {
- public static string UserID;
-
- }
Now, you can access it from anywhere in your forms after assigning a value to it.
- Global.UserID = comboBox1.Text.ToString();
You can use it in any form, as shown below.
- if(Global.UserID == "abdulateef")
- {
- dataGridView1.Refresh();
- string ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver};Server=localhost;Database="";User Id="";Password=";
- string query = "Select filename, encfile, password,date,username FROM encinfor";
- OdbcConnection conn = new OdbcConnection(ConnectionString);
- conn.Open();
- try
- {
-
- DataSet ds = new DataSet();
- using(OdbcDataAdapter adapater = new OdbcDataAdapter(query, conn))
- {
- adapater.Fill(ds);
- dataGridView1.DataSource = ds.Tables[0];
- }
- }
- catch(Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
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.
- class Global
- {
- public static string UserID;
- public static string Status;
- public static string Adim;
-
- }
Thanks, I hope it helps.