-2

I have created a class UserInfo and I have set values on user login response, now I don't know how to access those values in another part of my app (another form).

Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MYCUSTOMAPP
{
    class UserInfo
    {
        public string userId;
        public string userType;
        public string userName;
        public string userUserName;
        public string userPhone;
        public string userIdCard;
    }
}

Login (set values to class stings)

//....
SqlDataReader result = cmd.ExecuteReader();
if (result.HasRows)
{
  while (result.Read())
  {
    UserInfo loggedUser = new UserInfo();
    loggedUser.userId = result.GetValue(result.GetOrdinal("Id")).ToString();
    loggedUser.userName = result.GetValue(result.GetOrdinal("Name")).ToString();
    loggedUser.userType = result.GetValue(result.GetOrdinal("UserType")).ToString();
    loggedUser.userUserName = result.GetValue(result.GetOrdinal("UserName")).ToString();
    loggedUser.userPhone = result.GetValue(result.GetOrdinal("Phone")).ToString();
    loggedUser.userIdCard = result.GetValue(result.GetOrdinal("IdCard")).ToString();
  }
}
// the rest...

Question

Now let say I am in MainWindow form, how can I get value of userId for instance?

Update

Logic

  1. User login
  2. Store user data in class (or anything else that you might suggest)
  3. Get those user data globally in my app so I don't need to call database each time I need user info (it will be presented already)

Update 2

My login function

using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYCUSTOMAPPDatabaseString"].ConnectionString))
{
    if (cn.State == ConnectionState.Closed)
        cn.Open();
    using (DataTable dt = new DataTable())
    {
        using (SqlCommand cmd = new SqlCommand("dbo.LoginUser", cn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@UserName", usernameBox.Text);
            cmd.Parameters.AddWithValue("@Password", passwordBox.Text);

            SqlDataReader result = cmd.ExecuteReader();
            if (result.HasRows)
            {
                while (result.Read())
                {
                    // Name of logged user from database (this is database response)
                    Console.WriteLine(result.GetValue(result.GetOrdinal("Name")));

                    // Add logged user info to `UserInfo` class
                    UserInfo loggedUser = new UserInfo();
                    loggedUser.userId = result.GetValue(result.GetOrdinal("Id")).ToString();
                    loggedUser.userName = result.GetValue(result.GetOrdinal("Name")).ToString();
                    loggedUser.userType = result.GetValue(result.GetOrdinal("UserType")).ToString();
                    loggedUser.userUserName = result.GetValue(result.GetOrdinal("UserName")).ToString();
                    loggedUser.userPhone = result.GetValue(result.GetOrdinal("Phone")).ToString();
                    loggedUser.userIdCard = result.GetValue(result.GetOrdinal("IdCard")).ToString();


                    MainWindow mainWindow = new MainWindow();
                    this.Hide();
                    mainWindow.ShowDialog();
                    Show();
                }
            }
            else
            {
                cn.Close();
                MessageBox.Show("Your credentials are not match!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
mafortis
  • 6,750
  • 23
  • 130
  • 288
  • 1
    With each iteration of the `while` loop, the code creates a new `UserInfo` object, then does nothing with it. When the code exits the `while` loop… `loggedUser` will no longer exist. I am guessing you would want to create a collection like a `List` to add each `UserInfo` to with each iteration. – JohnG Aug 03 '21 at 08:59
  • @JohnG no It's a single user app, I don't want a list, I just want logged user info, when they logout it will be clear till next login – mafortis Aug 03 '21 at 09:00
  • Then store the UserInfo object somewhere, e.g. in a field or property. – Klaus Gütter Aug 03 '21 at 09:02
  • I am not sure what you mean by the last comment. My point is that `UserInfo loggedUser = new UserInfo();` … `loggerUser` ONLY exist inside the `while` loop. Once the `while` loop exits, `loggedUser` will no longer exist. So you could not access it from anywhere once the `while` loop ends. – JohnG Aug 03 '21 at 09:05
  • @JohnG my comment mostly was about this part you mentioned `List` and let me add logic to my question maybe it helps – mafortis Aug 03 '21 at 09:07
  • @KlausGütter sorry I didn't understand what you're exactly saying! – mafortis Aug 03 '21 at 09:22
  • @JohnG see my update please – mafortis Aug 03 '21 at 09:23
  • You should make `loggedUser` a global variable. It looks like the posted code is getting ALL the user’s info from the DB. But how is the code getting the user’s name from the LOGIN? As I comment, the posted code is simply looping through the user info objects returned from the DB…. But your code does NOTHING with them…. Like check to see if the user’s name the USER type in the Login matches one of the users in the DB. – JohnG Aug 03 '21 at 09:27
  • @JohnG OK let me share my login code so it becomes more clear to you. (PS: this is response of login function) – mafortis Aug 03 '21 at 09:28
  • @JohnG see my update code and you will understand it now. – mafortis Aug 03 '21 at 09:31
  • Hmmm… if this is working for you then great. I suggest you change the line of code that creates the `MainWindow` … `MainWindow mainWindow = new MainWindow();` … to send over the `UserInfo` `loggedUser` to the `MainWindow` like… `MainWindow mainWindow = new MainWindow(loggedUser);` … Obviously you will need to modify the `MainWindow`s constructor to accept the passed in `UserInfo` object. In the `MainWindow` form, create a global `UserInfo` variable and set it to the passed in `UserInfo` object. – JohnG Aug 03 '21 at 09:44
  • @JohnG Ok here I have 2 questions: 1- How do I make global `UserInfo` variable (which is basically my question) 2- If I already have global `UserInfo` I can access it in `MainWindow` (It's global already) then why should I modify my `MainWindow mainWindow = new MainWindow();` ? – mafortis Aug 03 '21 at 09:47
  • Hmm… 1) set the line of code… `UserInfo loggedUser;` … OUTSIDE all methods in the Login form but INSIDE the Forms class definition. This makes the variable accessible to all the methods in the form. … 2) _”2- If I already have global UserInfo I can access it in MainWindow (It's global already) then why should I modify my MainWindow mainWindow = new MainWindow();”_ … because the `loggedUser` in the `MainWindow` form is NOT the same `loggedUser` in the Login form. How could it be the same? The `MainWindow` knows nothing about the `LoginForm` variables... unless we pass it to it. – JohnG Aug 03 '21 at 09:59
  • `2` And that's exactly why I created this class in first place to have temporary storage of user data (something like `LocalStorage` in web browsers or `sessions`) that's how it suppose to `MainWindow->loggedUser` data will be the same data that `Login->loggedUser` has set previously. – mafortis Aug 03 '21 at 10:03
  • Well… you are mixing environments here. As far as `WinForms` goes… One `Form` knows nothing about another `Form`… as it should be. You can certainly create global variables that are accessible to ALL forms in a project, however, this is often unnecessary as passing data between forms is fairly simple and straight forward. I can only say you are mistaken to think that the variables in one `Form` would be accessible in some other `Form`. The class sounds OK, it may contain many properties, and it will be easier to pass ONE `UserInfo` object as opposed to all the individual properties. – JohnG Aug 03 '21 at 10:15
  • @JohnG So I am right for using `class` for this purpose right? and what it's in my mind is when user login, store his data in `class`, and later access those data by the class in other forms. `The thing is` that I don't really need to use user info in my `MainWindow` form but in another form. my `MainWindow` just happen to be open as first form after login (not necessarily need to use those data in there). And all I'm asking is: **How do I get my class data in other forms (any form except `MainWindow`)**? – mafortis Aug 03 '21 at 10:21
  • If `MainWindow` opens another `Form`(s) that needs the `UserInfo`… then you will still need to pass the `UserInfo` to the `MainWindow`… then it can pass the `UserInfo` on to the other form(s) that need it.. You would do this the same way as previously described. – JohnG Aug 03 '21 at 10:27
  • @JohnG I've solved my issue and share the code below, thank you. – mafortis Aug 03 '21 at 10:30

2 Answers2

-1

I think you can pass it as the parameters when you call another form's constructor, if you directly call that form. Like in this case : Communicate between two windows forms in C#

However, if you need to load it later on, you can either store it as user settings: https://www.youtube.com/watch?v=P432z8q9iVE. Or even more structural approach is store the data in database like MySQL, MSSQL, or another database that you can put when user click the call to action button.

marcboo
  • 1
  • 1
-1

Solved

I have changed my class to the following

class UserInfo
    {
        private string userId1;
        private static string userType1;
        private static string userName1;
        private static string userUserName1;
        private static string userPhone1;
        private static string userIdCard1;

        public string GetuserId()
        {
            return userId1;
        }
        public void SetuserId(string value)
        {
            userId1 = value;
        }

        public string GetuserType()
        {
            return userType1;
        }
        public void SetuserType(string value)
        {
            userType1 = value;
        }

        public string GetuserName()
        {
            return userName1;
        }
        public void SetuserName(string value)
        {
            userName1 = value;
        }

        public string GetuserUserName()
        {
            return userUserName1;
        }
        public void SetuserUserName(string value)
        {
            userUserName1 = value;
        }

        public string GetuserPhone()
        {
            return userPhone1;
        }
        public void SetuserPhone(string value)
        {
            userPhone1 = value;
        }

        public string GetuserIdCard()
        {
            return userIdCard1;
        }
        public void SetuserIdCard(string value)
        {
            userIdCard1 = value;
        }
    }

And changed my code in login response to:

while (result.Read())
{
  UserInfo loggedUser = new UserInfo();
  loggedUser.SetuserId(result.GetValue(result.GetOrdinal("Id")).ToString());     
 loggedUser.SetuserName(result.GetValue(result.GetOrdinal("Name")).ToString());
loggedUser.SetuserType(result.GetValue(result.GetOrdinal("UserType")).ToString());
     loggedUser.SetuserUserName(result.GetValue(result.GetOrdinal("UserName")).ToString());
loggedUser.SetuserPhone(result.GetValue(result.GetOrdinal("Phone")).ToString());
loggedUser.SetuserIdCard(result.GetValue(result.GetOrdinal("IdCard")).ToString());
}

Now I can get my values in any form like:

UserInfo loggedUser = new UserInfo();
loggedUser.GetuserName(); // will return logged user name
mafortis
  • 6,750
  • 23
  • 130
  • 288
  • I do not see how the posted code is going to solve the issue in relation to one form gaining access to another forms variables. But if it works for you… then go for it. Good Luck. – JohnG Aug 03 '21 at 10:35
  • @JohnG is not about forms accessing each others variables, is about forms accessing class variables. – mafortis Aug 03 '21 at 10:36
  • @JohnG don't worry about it ;) – mafortis Aug 03 '21 at 10:39