Hi bigbear,
Instead of returning boolean value from UserLogin function return string or integer value based on your datatype.
Then you can check the condition on button click for null or empty vale and fetch the User details.
Refer the below modified code.
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 (!string.IsNullOrEmpty(SQLuserAccess.UserLogin(txtUsername.Text, txtPassword.Password)))
{
MessageBox.Show("Login success");
string userId = SQLuserAccess.UserLogin(txtUsername.Text, txtPassword.Password);
User user = new User();
user = SQLuserAccess.GetUserById(Convert.ToInt32(userId));
}
else
{
MessageBox.Show("Login Failed");
}
}
}
}
public static string UserLogin(string username, string password)
{
string result;
string SQLloginQuery = "SELECT UserId 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();
result = Convert.ToString(cmdLogin.ExecuteScalar());
}
catch (Exception ex)
{
ex.Message.ToString();
throw ex;
}
finally
{
connection.Close();
}
return result;
}
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 = 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();
}
}