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
- User login
- Store user data in class (or anything else that you might suggest)
- 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);
}
}
}
}