非常感谢!
Thank you very much! You're fantastic!
Is it possible to write it this way? Use the database to verify the account password, verify successfully to log in, if it is not in the database then it will automatically register, if the password is wrong then it will show to re-enter the password?
==========================================================================
private void BtnLogin_Click(object sender, RoutedEventArgs e)
{
try
{
string connectionString = "YourConnectionStringHere";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM Users WHERE Username =
username";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("
username", UsernameCBOX.USERNAME.Text);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
string storedPassword = reader["Password"].ToString();
if (storedPassword == PasswordCBOX.PASSWORD.Password)
{
// 4. 存储登录信息
Statics.LoginId = UsernameCBOX.USERNAME.Text;
Statics.LoginPw = PasswordCBOX.PASSWORD.Password;
Hide();
}
else
{
// 6. 提示密码错误
ShowLoginError("Incorrect password. Please try again.");
}
}
}
else
{
// 5. 注册新用户
RegisterNewUser();
}
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void RegisterNewUser()
{
try
{
string connectionString = "YourConnectionStringHere";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO Users (Username, Password) VALUES (
username,
Password)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("
username", UsernameCBOX.USERNAME.Text);
command.Parameters.AddWithValue("
Password", PasswordCBOX.PASSWORD.Password);
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected > 0)
{
// 4. 存储登录信息
Statics.LoginId = UsernameCBOX.USERNAME.Text;
Statics.LoginPw = PasswordCBOX.PASSWORD.Password;
Hide();
}
else
{
ShowLoginError("User registration failed. Please try again.");
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ShowLoginError(string errorMessage)
{
MessageBox.Show(errorMessage);
}