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

如何检测DataGridView指定必填列空值并在保存时弹窗告警?

C# WinForm DataGridView 必填字段校验实现

需求说明

  • DataGridView1的BilgNo、VarlikSahibi、IP三列为必填项,不允许为空
  • 点击保存按钮时必须检测这三列是否存在空值,若存在则弹窗告警
  • 从SQL拉取数据后新增内容时,同样需要检测指定列的空值并告警

用户原有问题代码

private void btn_Save_Click(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand("Select * from Envanter where BilgNo,VarlikSahibi,IP", baglanti);
    cmd.Parameters.AddWithValue("BilgNo", dataGridView1);
    cmd.Parameters.AddWithValue("VarlikSahibi", dataGridView1);
    cmd.Parameters.AddWithValue("IP", dataGridView1);

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        commandBuilder = new SqlCommandBuilder(da);
        da.Update(tablo);
        MessageBox.Show("Saved");
        Envanter();

        return;
        
        /*
        if (dataGridView1.Rows.Cells[1].Value == null | Convert.ToString(row.Cells[1].Value) | string.IsNullOrEmpty)
        {
            DialogResult dr = MessageBox.Show("pls no empty", "Warn!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        return;
        */
        
    }
}

问题分析

  1. SQL语句语法错误:where子句写法不正确,此处不需要额外查询,直接校验DataGridView数据即可
  2. 参数绑定错误:将整个DataGridView控件作为参数传递,逻辑完全错误
  3. 校验逻辑被注释且实现错误:原有注释的判断条件语法错误,未覆盖所有空值场景
  4. 循环内直接执行保存并返回:未遍历所有行进行校验就完成了保存操作

修正后的代码

private void btn_Save_Click(object sender, EventArgs e)
{
    // 遍历DataGridView的每一行,排除自带的空白新增行
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.IsNewRow) continue;

        // 获取三列值并处理空值、空白字符串
        string bilgNo = row.Cells["BilgNo"].Value?.ToString().Trim() ?? string.Empty;
        string varlikSahibi = row.Cells["VarlikSahibi"].Value?.ToString().Trim() ?? string.Empty;
        string ip = row.Cells["IP"].Value?.ToString().Trim() ?? string.Empty;

        // 校验必填项是否为空
        if (string.IsNullOrEmpty(bilgNo) || string.IsNullOrEmpty(varlikSahibi) || string.IsNullOrEmpty(ip))
        {
            MessageBox.Show($"第{row.Index + 1}行的必填项不能为空!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
    }

    // 校验通过后执行数据库更新
    try
    {
        commandBuilder = new SqlCommandBuilder(da);
        da.Update(tablo);
        MessageBox.Show("数据保存成功!");
        Envanter(); // 刷新DataGridView数据
    }
    catch (Exception ex)
    {
        MessageBox.Show($"保存失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

关键说明

  1. 空值覆盖:通过?.ToString().Trim()处理null值和空白字符串,用string.IsNullOrEmpty完成空值判断
  2. 新增行过滤:跳过IsNewRow标记的空白行,避免无意义校验
  3. 定位提示:提示具体行号,方便用户快速定位问题
  4. 异常处理:捕获数据库操作异常,避免程序崩溃并给出明确错误信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:50:27