WPF健身应用数据库用户删除功能失效问题求助
问题
我在学校作业中需要开发一款健身应用,主页面通过以下代码将文本框的用户名传入Settings类:
WPF_login.Pages.Settings s = new WPF_login.Pages.Settings(txtUsername.Text);
但在Settings页面点击删除按钮时,无法删除对应用户。相关代码如下:
namespace WPF_login.Pages { /// <summary> /// Interaction logic for Settings.xaml /// </summary> class Person { public string name; public string getName(string namel) { return name; } } public partial class Settings : Page { public string name; private SqlConnection connection; public Settings(string loggedUser) { InitializeComponent(); // Save the value of loggedUser in the name variable name = loggedUser; Person p = new Person(); p.getName(loggedUser); string connectionString = "Data Source=DILEEKALAPTOP;Initial Catalog = FitnessGuidDB; Integrated Security = True;"; connection = new SqlConnection(connectionString); bool loggedUserExists = CheckLoggedUserExists(loggedUser); if (!loggedUserExists) { MessageBox.Show($"Success: {p.name} exists", "Infromation", MessageBoxButton.OK, MessageBoxImage.Information); } } private bool CheckLoggedUserExists(string luser) { bool userExists = false; try { // Open the connection to the database connection.Open(); // Create a new SqlCommand object to execute the SELECT statement SqlCommand command = new SqlCommand($"SELECT * FROM UserRegister WHERE U_name = '{name}'", connection); // Execute the query and get the results SqlDataReader reader = command.ExecuteReader(); // Check if there are any rows in the result set if (reader.HasRows) { userExists = true; } // Close the reader reader.Close(); } catch (Exception ex) { // Handle any errors that occur MessageBox.Show($"Error: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } finally { // Close the connection to the database connection.Close(); } return userExists; } public Settings() { } private void mobilechangebtn_Click(object sender, RoutedEventArgs e) { } private void lbl_welcome_Loaded(object sender, RoutedEventArgs e) { } private void lbl_welcome_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { } private void Border_Loaded(object sender, RoutedEventArgs e) { lbl_welcome.Content = name; } private void mobilechangebtn_Click_1(object sender, RoutedEventArgs e) { } private void deleteuserbtn_Click(object sender, RoutedEventArgs e) { Settings settings = new Settings(); string loggedUser = settings.name; // MessageBox.Show($"Success: {loggedUser} exists", "Infromation", MessageBoxButton.OK, MessageBoxImage.Information); string LoggedUser = "dummy"; string connectionString = "Data Source=DILEEKALAPTOP;Initial Catalog = FitnessGuidDB; Integrated Security = True;"; connection = new SqlConnection(connectionString); try { // Open the connection to the database connection.Open(); // Create a new SqlCommand object to execute the DELETE statement SqlCommand command = new SqlCommand($"DELETE FROM UserRegister WHERE U_name = '{LoggedUser}'", connection); // Execute the query command.ExecuteNonQuery(); // Set LoggedUser to null or an empty string to delete it LoggedUser = null; // or LoggedUser = ""; // Show a success message to the user MessageBox.Show($"Successfully deleted user: {LoggedUser}", "Success", MessageBoxButton.OK, MessageBoxImage.Information); WPF_login.CreateUser c = new WPF_login.CreateUser(); c.Show(); //this.Hide(); } catch (Exception ex) { // Handle any errors that occur MessageBox.Show($"Error: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } finally { // Close the connection to the database connection.Close(); } } } }
我尝试过创建名为Person的自定义类并将其name设为登录用户名,也尝试过使用属性,但都无法解决问题。请问我哪里出错了?
问题分析与修复方案
1. 删除按钮事件的核心错误
在deleteuserbtn_Click方法里,你犯了两个致命错误:
- 新建了一个空的
Settings实例,这个实例的name字段根本没有赋值,获取不到当前登录用户 - 硬编码了
LoggedUser = "dummy",直接导致删除的是名为dummy的用户,而非当前登录用户
修复后的删除按钮代码:
private void deleteuserbtn_Click(object sender, RoutedEventArgs e) { // 直接使用当前页面已保存的name字段,无需新建实例 string loggedUser = name; if (string.IsNullOrEmpty(loggedUser)) { MessageBox.Show("无法获取当前登录用户信息", "错误", MessageBoxButton.OK, MessageBoxImage.Error); return; } string connectionString = "Data Source=DILEEKALAPTOP;Initial Catalog = FitnessGuidDB; Integrated Security = True;"; // 使用using块自动管理连接生命周期,无需手动关闭 using (SqlConnection connection = new SqlConnection(connectionString)) { try { connection.Open(); // 使用参数化查询避免SQL注入,同时确保用户名正确传入 SqlCommand command = new SqlCommand("DELETE FROM UserRegister WHERE U_name = @UserName", connection); command.Parameters.AddWithValue("@UserName", loggedUser); int rowsAffected = command.ExecuteNonQuery(); if (rowsAffected > 0) { MessageBox.Show($"成功删除用户: {loggedUser}", "成功", MessageBoxButton.OK, MessageBoxImage.Information); WPF_login.CreateUser c = new WPF_login.CreateUser(); c.Show(); NavigationService?.GoBack(); // 返回上一页 } else { MessageBox.Show("未找到该用户,删除失败", "提示", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { MessageBox.Show($"错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error); } } }
2. Person类完全无效
你创建的Person类逻辑混乱:getName方法接收参数但从未给p.name赋值,调用后p.name依然是null,这个类完全没起到作用,直接删除即可。
3. CheckLoggedUserExists方法的逻辑错误
- 方法传入了
luser参数,但SQL语句里用的是类的name字段,参数完全没用到 - 判断逻辑颠倒:
!loggedUserExists时提示用户存在,实际应该是loggedUserExists为true时才提示
修复后的检查方法:
private bool CheckLoggedUserExists(string luser) { bool userExists = false; string connectionString = "Data Source=DILEEKALAPTOP;Initial Catalog = FitnessGuidDB; Integrated Security = True;"; using (SqlConnection connection = new SqlConnection(connectionString)) { try { connection.Open(); // 使用参数化查询,用传入的luser参数 SqlCommand command = new SqlCommand("SELECT 1 FROM UserRegister WHERE U_name = @UserName", connection); command.Parameters.AddWithValue("@UserName", luser); // 用ExecuteScalar判断是否存在,比DataReader更高效 object result = command.ExecuteScalar(); userExists = result != null; } catch (Exception ex) { MessageBox.Show($"错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error); } } return userExists; }
4. 修正Settings构造函数
移除无用的Person类,修正提示逻辑:
public Settings(string loggedUser) { InitializeComponent(); name = loggedUser; bool loggedUserExists = CheckLoggedUserExists(loggedUser); if (loggedUserExists) { MessageBox.Show($"成功: {name} 存在", "信息", MessageBoxButton.OK, MessageBoxImage.Information); } else { MessageBox.Show($"用户 {name} 不存在", "提示", MessageBoxButton.OK, MessageBoxImage.Warning); } }
内容的提问来源于stack exchange,提问作者Dileeka Dasanayake
相关产品推荐
相关产品推荐

