• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 326
  • Last Modified:

getting data across different forms in C#

Hello experts - merry Christmas (again),

I have a form which acts as a login screen. It has a UserName and PassWord text boxes which it uses to check the entered name and password against the ones stored in a database table.

My question is this:
Once the user is logged in, is there a way I can capture his name and have it accessible from other forms?
I know that C# doesn't support global variables and I am trying to think of a way to achieve the above task. Can you help shed some light on how to go about this?

Thank you
0
adamtrask
Asked:
adamtrask
  • 4
  • 3
1 Solution
 
käµfm³d 👽Commented:
0
 
adamtraskAuthor Commented:
the above example is a little too cryptic for my humble beginnings.

I do understand the Class concept, and I am trying to using as best as I can.

for example in the code below is a class called  "Logining". Its job is to check the User ID and password against the names and passwords stored in a database.... in that Class I tried to capture the name of the Logged in user by placing a public variable at the very top of the class called LoggedUser.
Once the user name is retrieved by the class code, I assign the logged in user's  name to that public variable.

And, from inside one of the forms in the application (a form called Notes) I try to access that public variable in the class in the following manner.  

 private void Notes_Load(object sender, EventArgs e)
        {
            Logining getUserName = new Logining();
            string myName = getUserName.LoggedUser;
            MessageBox.Show(myName);
        }
However the MessageBox comes up empty.

Please take a look at the class code below
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public class Logining
    {
        public string LoggedUser;
        private Int32 _userID;
        private string _loginName;
        private string _password;
        private string _securityLevel;
        public Int32 userID
        {
            get { return _userID; }
            set { _userID = value; }
        }

        public string LoginName
        {
            get { return _loginName; }
            set { _loginName = value; }
        }
        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }
        public string SecurityLevel
        {
            get { return _securityLevel; }
            set { _securityLevel = value; }
        }
        public void Login(string loginName, string password)
        {
            LoginName = loginName;
            Password = password;
            // retrieve data from database
            SqlConnection con = default(SqlConnection);
            SqlCommand com = default(SqlCommand);
            con = new SqlConnection("Server=PC;Database=HelpDesk;integrated security=True");
            com = new SqlCommand("Select * from Users", con);
            // com = new SqlCommand("Select UserName,PassWord from Users", con);
            con.Open();
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                if (loginName == Convert.ToString(reader["UserName"]) && password == Convert.ToString(reader["PassWord"]))
                {
                    LoggedUser = loginName;
                    userID = Convert.ToInt32(reader["ID"]);
                    SecurityLevel = "Good"; //It is already a string so no need to use ToString() function
                    break; // TODO: might not be correct. Was : Exit Do
                }
                else
                {
                    SecurityLevel = "Failed";

                }

            }
            reader.Close();
            con.Close();
        }
    }


}

Open in new window

0
 
käµfm³d 👽Commented:
Cryptic? I'll grant you it's long, but that's only because of the code examples and the fact that there are multiple ways to share data...  I tried to lay out the information as plainly as I could   ; )

And, from inside one of the forms in the application (a form called Notes) I try to access that public variable in the class in the following manner.  

 private void Notes_Load(object sender, EventArgs e)
        {
            Logining getUserName = new Logining();
            string myName = getUserName.LoggedUser;
            MessageBox.Show(myName);
        }
However the MessageBox comes up empty.

As I discussed in my article, you have to be aware of variable scope. In addition to that, for your particular example you will need to be aware of object lifetime.

Let's approach it from this angle:  your Logging class has a Login method, yes? Where do you call this method? It's certainly not at the code where you display the MessageBox, because I don't see any place in that block of code where you call it. That doesn't mean you never called it--I'm certain you did. Your problem is that you are trying to access instance data from multiple instances. Instance data does not persist between two different instances of a class. In order to share data between two instances, you either need to let the two instances interact with each others' public properties and methods, or provide some static members to be accessible to all instances (both of which are covered in my article).

As a quick fix, you can do something like this:

using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public class Logining
    {
        public static string LoggedUser;
        private Int32 _userID;
        private string _loginName;
        private string _password;
        private string _securityLevel;
        public Int32 userID
        {
            get { return _userID; }
            set { _userID = value; }
        }

        public string LoginName
        {
            get { return _loginName; }
            set { _loginName = value; }
        }
        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }
        public string SecurityLevel
        {
            get { return _securityLevel; }
            set { _securityLevel = value; }
        }
        public void Login(string loginName, string password)
        {
            LoginName = loginName;
            Password = password;
            // retrieve data from database
            SqlConnection con = default(SqlConnection);
            SqlCommand com = default(SqlCommand);
            con = new SqlConnection("Server=PC;Database=HelpDesk;integrated security=True");
            com = new SqlCommand("Select * from Users", con);
            // com = new SqlCommand("Select UserName,PassWord from Users", con);
            con.Open();
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                if (loginName == Convert.ToString(reader["UserName"]) && password == Convert.ToString(reader["PassWord"]))
                {
                    LoggedUser = loginName;
                    userID = Convert.ToInt32(reader["ID"]);
                    SecurityLevel = "Good"; //It is already a string so no need to use ToString() function
                    break; // TODO: might not be correct. Was : Exit Do
                }
                else
                {
                    SecurityLevel = "Failed";

                }

            }
            reader.Close();
            con.Close();
        }
    }
}

Open in new window


...and then modify you MessageBox code as such:

private void Notes_Load(object sender, EventArgs e)
{
    string myName = Logging.LoggedUser;
    MessageBox.Show(myName);
}

Open in new window


This is just a quick fix, and it I present it only to demonstrate functionality. I don't think making LoggedUser static is the best answer for your situation, but it would work. Know that marking a member as static means that member is shared among all instances of the class. Any instance is free to change the value of the static member at any point in your code. This may yield unexpected results. Also note how I accessed the static member by using the class name (Logging) rather than an instance variable in line 3 above. You don't need an instance of a variable in order to access static members.

My suggestion is to use one of the public properties/methods approaches I outlined in my article.
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
SAMIR BHOGAYTAFreelancer and IT ConsultantCommented:
Hello,

Yes, you can access the name of logged in person with the help of Session.Contents("NameOfUser"). You can store the name of the person from the database into this session variable and user this variable any where into the whole application. With the name of session variable.
0
 
adamtraskAuthor Commented:
kaufmed:
Thank you so much for your explanation. I believe it was my mind that was some what foggy yesterday.
Well, it was a holiday and I was forcing it to work when it was supposed to rest.....:)

I am trying to learn to use the public properties and methods outlined in your article.
I hope to be able to get more of your guidance when I need it.
Thanks

samirbhogayta: I believe you are talking about a web application. This is a Windows application. I wish we had a Session tool in a Window application. thanks

0
 
adamtraskAuthor Commented:
Thank you
0
 
käµfm³d 👽Commented:
I wish we had a Session tool in a Window application.
You could certainly mimic one. If you use a static class, you could have something like:

public static class MyFormsSession
{
    private static Dictionary<string, object> storage = new Dictionary<string, object>();

    public static object GetValue(string key)
    {
        return (storage.ContainsKey(key) ? storage[key] : null);
    }

    public static void SetValue(string key, object value)
    {
        if (storage.ContainsKey(key))
        {
            storage[key] = value;
        }
        else
        {
            storage.Add(key, value);
        }
    }
}

Open in new window


It's not an exact match, but it is equivalent. Now you can access this "session" anywhere within your application. Using the class would go something like this:

MyFormsSession.SetValue("a color string", "red");
MyFormsSession.SetValue("a rectangle", new Rectangle());

Rectangle r = (Rectangle)MyFormsSession.GetValue("a rectangle");
string c = MyFormsSession.GetValue("a color string") as string;

Open in new window


The ASP.NET Session object allows us to using indexing notation to retrieve elements:

string c = Session["a color string"] as string;

Open in new window


...but unfortunately, we cannot overload the indexing operator ( [] ) on a static class. We must therefore approximate with "get" and "set" methods--which in actuality is what properties are turned into when you compile your application!

Please note: The above code is not thread-safe. If you have more than one thread interacting with that class, you may run into race conditions. I kept the class simple since you indicating you are starting out with C#. If you only have one thread, then the above is fine to use.
0
 
adamtraskAuthor Commented:
Thank you very much kaufmed:

Yes, I am starting out with C# and for the last three weeks I've been working on turning an Asp.net (vb.net) application into a C# one.

It was also my first asp.net application, which means I am a novice programmer, not just a novice  C# programmer.

I am going to try out the suggested code.... I am sure it will be a while before I start fiddling with threads. Thank you.



0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now