You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# + SQL Server ListBox用户增删改操作中ID选取报错问题咨询

问题原因及修复方案

核心错误点

  1. 获取用户ID的方式错误:ListaUtilizatori.SelectedItems.ToString() 得到的是选中项集合的类名,并非目标用户ID,转换为int时自然触发格式错误。
  2. SQL语法错误:int类型的id字段在SQL语句中被加了单引号,被数据库识别为字符串类型,与列的int类型不匹配,触发转换报错。
  3. 存在SQL注入风险:更新、删除逻辑没有和新增逻辑保持一致使用参数化查询,手写拼接SQL既容易出语法问题也存在安全隐患。
  4. 校验逻辑缺失:没有先判断ListBox是否存在选中项,仅校验文本框非空会导致空引用异常。

修复步骤

第一步:调整ListBox绑定逻辑

首先修改fill_listbox()方法,绑定ListBox时同时存储用户ID和显示用户名:

// fill_listbox方法内部绑定示例
SqlDataAdapter da = new SqlDataAdapter("select id, username from Users", con);
DataTable dt = new DataTable();
da.Fill(dt);
ListaUtilizatori.DataSource = dt;
ListaUtilizatori.DisplayMember = "username"; // 列表显示用户名
ListaUtilizatori.ValueMember = "id"; // 隐藏存储对应用户ID

第二步:修改编辑按钮逻辑

private void EditUser_Click(object sender, EventArgs e) //编辑用户按钮
{
    // 先校验选中状态和输入完整性
    if (ListaUtilizatori.SelectedValue == null 
        || string.IsNullOrWhiteSpace(NumeUtilizator.Text) 
        || string.IsNullOrWhiteSpace(Parola.Text))
    {
        MessageBox.Show("请先选中要编辑的用户并补全所有字段");
        return;
    }
    int userId = Convert.ToInt32(ListaUtilizatori.SelectedValue);
    // 使用参数化查询,避免拼接SQL的问题
    SqlCommand cmd = new SqlCommand("UPDATE Users SET username = @username, password = @password, role = @role WHERE id = @id", con); 
    cmd.Parameters.AddWithValue("@username", NumeUtilizator.Text);
    cmd.Parameters.AddWithValue("@password", Parola.Text);
    cmd.Parameters.AddWithValue("@role", rol);
    cmd.Parameters.AddWithValue("@id", userId);

    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();

    MessageBox.Show("用户编辑成功");
    NumeUtilizator.Text = "";
    Parola.Text = "";
    fill_listbox();
}

第三步:修改删除按钮逻辑

private void DeleteUser_Click(object sender, EventArgs e) //删除用户按钮
{
    if (ListaUtilizatori.SelectedValue == null)
    {
        MessageBox.Show("请先选中要删除的用户");
        return;
    }
    int userId = Convert.ToInt32(ListaUtilizatori.SelectedValue);
    SqlCommand cmd = new SqlCommand("DELETE FROM Users WHERE id = @id", con); 
    cmd.Parameters.AddWithValue("@id", userId);

    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();

    MessageBox.Show("用户删除成功");
    NumeUtilizator.Text = "";
    Parola.Text = "";
    fill_listbox();
}

内容的提问来源于stack exchange,提问作者Chriss_1982

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:15:04