Hello all,
I have a login method to check if a user is a member in my DB. My login method is only a bool and I am wondering how can I grab that current users data so I can pass it to the next window. I am checking textboxes to see if the text is valid.
One way I know I could solve this is to change my login method so it returns a user then I would have that specific user but I would like to see if I could grab the user data by checking if the data is in the DB.
Here is what I have:
private void BtnLoginUser_Click(object sender, RoutedEventArgs e){
if (string.IsNullOrEmpty(txtUsername.Text)) {
MessageBox.Show("Enter your username.", "Empty", MessageBoxButton.OK, MessageBoxImage.Information); txtUsername.Focus();
return;
}
else if (string.IsNullOrEmpty(txtPassword.Password)) {
MessageBox.Show("Enter your password.", "Empty", MessageBoxButton.OK, MessageBoxImage.Information); txtPassword.Focus();
return;
}
else {
try {
if(SQLuserAccess.UserLogin(txtUsername.Text, txtPassword.Password)){
}
}
}
}
public static bool UserLogin(string username, string password) {
bool valid = false;
string SQLloginQuery = "SELECT * FROM Users WHERE Username=@username AND Password=@password";
SqlCommand cmdLogin = new SqlCommand(SQLloginQuery, connection);
cmdLogin.Parameters.AddWithValue("@username", username);
cmdLogin.Parameters.AddWithValue("@password", password);
try {
connection.Open();
int result = (int)cmdLogin.ExecuteScalar();
if (result > 0) {
valid = true;
MessageBox.Show("Login success");
}
else MessageBox.Show("Login Failed");
}
catch (Exception ex) {
ex.Message.ToString();
throw ex;
}
finally{
connection.Close();
}
return valid;
}
public static User GetUserById(int userId{
string SQLreadQuery = "SELECT Username, Password, IsAdmin, UserCreatedDate " +
"FROM Users WHERE UserId = " + userId;
SqlCommand cmdRead = new SqlCommand(SQLreadQuery, connection);
try{
connection.Open();
SqlDataReader reader = cmdRead.ExecuteReader(CommandBehavior.SingleRow);
if(reader.Read()){
User user = new User();
user.UserID = Convert.ToInt32(reader["UserId"]);
user.Username = reader["Username"].ToString();
user.Password = reader["Password"].ToString();
user.IsAdmin = Convert.ToBoolean(reader["IsAdmin"]);
user.UserCreatedDate = Convert.ToDateTime(reader["UserCreatedDate"]);
return user;
}
else{
return null;
}
}
catch(Exception ex){
ex.Message.ToString();
return null;
}
finally{
connection.Close();
}
}
What I have tried:
I know i can solve this by returning a User instead of Bool but i would like to see if i can do it like this instead
Maybe if i return a user object with GetUserById() then i could retrieve the data.
do i want to store the data in a datatable? or just in a client object