How to create a variable accessible in all forms?

3

In my application you will have a Login system. I want to create a variable to store the id of the user that is logged in, and that it can be accessed on all other forms.

I need this because in my database, each table has a field called usuario that will store the name of the user who saved the record in the database.

Whenever I want to use the variable in another form, I do so:

form meuLogin = new form();
meuLogin.idUsuario = tabela.id;

So I always create a new object of formLogin (which is where the variable idUsuario is stored) to be able to get the variable. Am I doing right or have a way to make a "global" variable?

    
asked by anonymous 05.01.2017 / 20:11

1 answer

8

One way to solve is by using a Singleton.

With a Singleton you can create a static class that would work as a sort of "Session and then store and retrieve information that the user needs during the lifetime of the application. You would probably feed the initial session data during Login .

    public sealed class Session
    {

        private static volatile Session instance;
        private static object sync = new Object();

        private Session() { }

        public static Session Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (sync)
                    {
                        if (instance == null)
                        {
                            instance = new Session();
                        }
                    }
                }
                return instance;
            }

        }

        /// <summary>
        /// Propriedade para o ID do usuario
        /// </summary>
        public int UserID { get; set; }

    }

To adjust the user ID, you would need to do something like this:

Session.Instance.UserID = 10;

Stop Recovering:

int ID = Session.Instance.UserID;

You can increment the class by adding new properties as needed.

    
05.01.2017 / 21:00