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))
{
//verify and enter username.
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");
}
}
}
}
//SQL login method
public static string UserLogin(string username, string password)
{
string result;
//SQL Login Query.
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;
}
//This is a method I use to get the user
public static User GetUserById(int userId)
{
string SQLreadQuery = "SELECT Username, Password, IsAdmin, UserCreatedDate " +
"FROM Users WHERE UserId = " + userId; //or SELECT each column or *.
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();
}
}