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

WinForms中DataGridView选中行填充文本框及数据增改删问题排查

问题分析与代码修复

你的dataGridView_StaffDetails_CellClick事件代码存在多处逻辑错误,导致运行报错或功能不符合预期,具体问题和修复方案如下:

核心问题点

  • 错误的数据源获取逻辑:点击DataGridView单元格时,无需重新查询数据库,直接从选中行提取数据即可。原代码反而查询整个类别的数据,导致文本框最终只会显示该类别最后一条记录。
  • 空引用风险:未判断comboBox_Type.SelectedItem是否为null就调用ToString(),触发空引用异常。
  • SQL注入隐患:直接拼接字符串生成SQL语句,存在安全风险(且此处根本不需要查询数据库)。
  • 数据库连接管理不当:未使用using语句自动释放连接,可能导致连接泄漏。
  • 字段名不匹配:表名为StaffDetails,但代码中使用Customer_FirstName这类字段名,大概率是字段名称拼写错误。

修复后的CellClick事件代码

private void dataGridView_StaffDetails_CellClick(object sender, DataGridViewCellEventArgs e)
{
    // 排除点击表头或空行的情况
    if (e.RowIndex < 0 || dataGridView_StaffDetails.Rows[e.RowIndex].IsNewRow)
        return;

    // 获取选中的行
    DataGridViewRow selectedRow = dataGridView_StaffDetails.Rows[e.RowIndex];

    // 将行数据填充到文本框,处理空值避免异常
    Txt_FirstName.Text = selectedRow.Cells["Staff_FirstName"].Value?.ToString() ?? string.Empty;
    Txt_LastName.Text = selectedRow.Cells["Staff_LastName"].Value?.ToString() ?? string.Empty;
    Txt_Username.Text = selectedRow.Cells["Username"].Value?.ToString() ?? string.Empty;
    Txt_Password.Text = selectedRow.Cells["Password"].Value?.ToString() ?? string.Empty;
    Txt_SalaryPerMonth.Text = selectedRow.Cells["Salary_Per_Month"].Value?.ToString() ?? string.Empty;
    
    // 设置ComboBox选中项
    string staffType = selectedRow.Cells["Staff_Type"].Value?.ToString() ?? string.Empty;
    comboBox_Type.SelectedItem = comboBox_Type.Items.Cast<string>().FirstOrDefault(item => item == staffType);

    // 启用更新/删除按钮
    Btn_Update.Enabled = true;
    Btn_Delete.Enabled = true;
}

补充:ComboBox选类别加载DataGridView的代码

要实现从ComboBox选择类别后加载对应数据到DataGridView,需编写ComboBox的SelectedIndexChanged事件,同时使用参数化查询避免SQL注入:

private void comboBox_Type_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox_Type.SelectedItem == null)
    {
        Btn_Search.Enabled = false;
        dataGridView_StaffDetails.DataSource = null;
        return;
    }

    Btn_Search.Enabled = true;
    string staffType = comboBox_Type.SelectedItem.ToString();

    // 使用using自动管理数据库连接和命令,避免资源泄漏
    using (SqlConnection connection = new SqlConnection("你的数据库连接字符串"))
    {
        string sql = "SELECT * FROM StaffDetails WHERE Staff_Type = @StaffType";
        using (SqlCommand cmd = new SqlCommand(sql, connection))
        {
            // 添加参数化查询,杜绝SQL注入
            cmd.Parameters.AddWithValue("@StaffType", staffType);

            try
            {
                connection.Open();
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                dataGridView_StaffDetails.DataSource = dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败:{ex.Message}");
            }
        }
    }
}

关键说明

  1. CellClick逻辑修正:直接从DataGridView选中行提取数据,既高效又符合“点击行填充文本框”的需求。
  2. 空值处理:用?.ToString() ?? string.Empty避免空值转换时的异常。
  3. 参数化查询:加载数据时使用参数化SQL,彻底避免SQL注入风险。
  4. 资源自动释放:用using语句包裹数据库连接和命令,确保资源自动释放,避免连接泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:15:08