[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1914
  • Last Modified:

Global Variables

I have a modal login dialog box that sets a string variable and then the dialog box closes.  (It is a login dialog box and if correct username and password, it sets the string to the value of the username.)  I need to be able to access the value of this variable from the main form of my application.  In C++ the modifier would be "external".  Then, this variable would be accessible anywhere in the application.  I need to be able to access the username from anywhere in the application so that the app will be able to determine the type of privileges the current user has when modifying the database.

Thanks in advance.
0
fly412s
Asked:
fly412s
  • 9
  • 6
  • 5
1 Solution
 
Timbo87Commented:
On the login form, add local variables for the user name and password, then add public properties that retrieve the values.

// Form1 class

private string username;

public string Username
{
     get
     {
          return username;
     }
     set
     {
          username = value;
     }
}

Store the text box values in the variables when they click OK. Then in the main form.

Form1 frm = new Form1();
if(frm1.ShowDialog() == DialogResult.OK)
{
     // do something with frm.Username
}
0
 
Timbo87Commented:
Small typo, that should be frm.ShowDialog(), not frm1.ShowDialog().
0
 
fly412sAuthor Commented:
That won't work because the main form calls the login form.  I do not have an "ok" button.  Just a "Login" button and "exit" button function to exit from the application.  The "login" button click event calls a query and if username and password are found, the login dialog box closes and allows the user access to the main application form.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Timbo87Commented:
It still works. You can perform all the user validation in the login form and still expose a username to the main form if it succeeds.
0
 
fly412sAuthor Commented:
I don't understand...Here is a portion of the code that calls the Login form.  

partial class MainForm : Form
      {
            LoginForm loginForm = new LoginForm();


            public MainForm()
            {
                  InitializeComponent();
                  loginForm.Show(this);
            }

      }

The MainForm needs to have the string Username established in the LoginForm.
0
 
Timbo87Commented:
loginForm.Show(this);
string username = loginForm.Username;

Once the user is authenticated in the login form, put the username in a publicly accessible property (in LoginForm). A form is just a class and can have properties just like any other class.
0
 
fly412sAuthor Commented:
I've already tried that suggestion.  It doesn't work.  Is there any modifier in c# that acts like the extern modifier in c++?
0
 
Timbo87Commented:
No offense, but you must be doing something wrong. I've used this technique to do exactly what you want to do before. Global variables like C++'s do not exist in .NET either.
0
 
ryerrasCommented:
You can do that. Its called static variable. Lets try this

In your MainForm

private static string _userName = null;
 public static string UserName
{
   get
   {
     return _userName;
   }
   set
   {
     _userName = value;
   }
}

In your child form, when the user is authenticated, just say MainForm.UserName= "username"; and you are done

Let me know if you got any questions
0
 
fly412sAuthor Commented:
Still not working.  Here is the code from the MainForm:

partial class MainForm : Form
      {

            private static string _userName = null;
            public static string UserName
            {
                  get
                  {
                        return _userName;
                  }
                  set
                  {
                        _userName = value;
                  }
            }


            public MainForm()
            {
                  InitializeComponent();

            }

            private void MainForm_Load(object sender, EventArgs e)
            {
                  LoginForm loginForm = new LoginForm();
                  loginForm.Show(this);
                  //MessageBox.Show(UserName);
            }

Here is the code from the LoginForm:

private void buttonLogin_Click(object sender, EventArgs e)
            {
                  try
                  {
                        conn = connMgr.OpenConnection();
                        OleDbCommand cmd = new OleDbCommand(
                              "SELECT Username, Password from Usernames "+
                              "WHERE Username LIKE ?", conn);
                        string userName = "%" + textBoxUserName.Text + "%";
                        cmd.Parameters.Add("User_Name", OleDbType.VarChar);
                        cmd.Parameters["User_Name"].Value = userName;
                        oleDbAdapter.SelectCommand = cmd;
                        oleDbAdapter.Fill(userDataSet, "Usernames");
                        if (userDataSet.Tables["UserNames"].Rows.Count > 0)
                        {
                              DataRow dr = userDataSet.Tables["UserNames"].Rows[0];
                              if (dr["Password"].ToString() == textBoxPassword.Text)
                              {
                                    MessageBox.Show("Successful Login");
                                    connMgr.CloseConnection();
                                    MainForm.UserName = textBoxUserName.Text;
                                    this.Close();
                              }//end password matches
                              else
                              {
                                    MessageBox.Show("Password does not match.");
                                    connMgr.CloseConnection();
                              }
                        }//end if successful username in database
                        if (userDataSet.Tables["UserNames"].Rows.Count == 0)
                        {
                              MessageBox.Show("Could not find username");
                              connMgr.CloseConnection();
                        }//end if unsuccessful username in database

                  }
0
 
fly412sAuthor Commented:
It seems as if when the application executes, the loginform is called first and then the mainform loads second so that there is never a chance for the UserName variable to be initialized by the loginform's username textbox.
0
 
ryerrasCommented:
This should work. Are you checking the user name in the main form after the child form closes. If you do whats the result. Please put break points and try to debug. Let me know if you get any error
0
 
ryerrasCommented:
Hmm now you know why its not happening, may be you should alter the way your forms load. May be you should load the main form first, then hide it and show the user the loginform only, after the authentication, make the visibility of the main form to true. That way, all the variables in the main form would still be available to the child form
0
 
fly412sAuthor Commented:
The program starts in the Program class as follows:

namespace Logbook
{
      static class Program
      {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  
                  Application.EnableVisualStyles();
                  Application.EnableRTLMirroring();
                  Application.Run(new MainForm());
            }
      }
}

As you can see, the MainForm is called first.  It is from within the MainForm that the LoginForm is called.  So, as far as I can tell, the MainForm should load first, then the LoginForm, since the LoginForm is called by the MainForm???????
0
 
ryerrasCommented:
It looks like that. But remember, this is all one thread. A thread returns only when its work is done, thats called synchronous programming. After invoke Application.Run(new MainForm()), it goes to the MainForm_Load, this method loads the child window, so you see the child form, you still havent seen the main form yet, since its load method is not finished yet. remember its still in the single thread, so its not returned to the user yet. Thats why you dont see the mainform until you close the child window
0
 
fly412sAuthor Commented:
OK, so what do you recommend to solve my dilema?
0
 
ryerrasCommented:
Well. a correction to what I said, your main form should be displayed, if the child form is a non modal form, which looks like it from the Show method. But I dont understand what is that argument "this" for Show method, I am not aware of a Show method which takes an argument.. Anyway, if any of this does not solve your problem

Put that static variable stuff in the child form instead of MainForm and after the user is authenticated, assign the user name to the child windows static variable.

 if (dr["Password"].ToString() == textBoxPassword.Text)
                         {
                              MessageBox.Show("Successful Login");
                              connMgr.CloseConnection();
                              LoginForm.UserName = textBoxUserName.Text;
                              this.Close();
                         }//end password matches

Dont worry, your static variable will still be there, even if you close the window. In your main form, access the user name as
LoginForm.UserName. It should work.
0
 
fly412sAuthor Commented:
The "this" is passed to the Show method as a "pointer" to the parent form, the MainForm.  Also, the problem of how the application loads itself is solved by calling the ShowDialog method of the LoginForm instead of the Show method.  The ShowDialog method seems to stop everything until that "dialog box" (the LoginForm) is closed.  Once the ShowDialog method is called, the application class (the Program class) stops executing until the ShowDialog returns (or closes, i.e., the "Login" button in the LoginForm is clicked).  Then the application continues loading the MainForm and the variable I need is exactly where you said it would be: MainForm.UserName.
0
 
ryerrasCommented:
so is everything ok now?
0
 
fly412sAuthor Commented:
Works great, thank you.  Did I make sense in the above explanation?
0

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

  • 9
  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now