How to create a variable accessible in all Forms?

Asked

Viewed 4,168 times

3

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

I need this because in my database, each table has a field called usuario which 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 from formLogin (which is where the variable idUsuario is stored) to be able to pick up the variable. I’m doing it right or has a way to make a variable "global"?

  • Turn her into static maybe? public static string exemplo { get; set;}. As long as there is no competition for this variable I believe that everything will be fine. I just don’t know if this is the best way to do it.

  • You should not create global variables. You can do what the above comment says, but you may have problems in concurrent environments. http://answall.com/q/21158/101. The question lacks more context to offer a suitable solution, or at least to say where to create this static variable. But if I get it, it’s not right at all.

  • changed the question

1 answer

10


One way to solve it is by using a Singleton.

With a Singleton you can create a static class that would act as a kind of "User Session" and there save and retrieve information that the user needs during the life of the application. You would probably feed the initial session data during the 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, just do something like:

Session.Instance.UserID = 10;

To recover:

int ID = Session.Instance.UserID;

You can increment the class by adding new properties you find necessary.

  • very good . tells me one thing: I add a new class to my project or put this code in a form?

  • 2

    @Italorodrigo always add classes in separate files to your project. This makes it easy to maintain together with your source control.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.