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

DataGridView校验重复值时触发NULLReferenceException空引用异常如何解决

问题原因

你遇到的空引用错误由两个核心问题触发:

  • DataGridView默认开启了「允许用户添加行」选项,末尾会自带一行空白待编辑行,该行所有单元格的Value属性均为null,直接调用.ToString()就会抛出对应异常
  • 若你之前手动录入过第一列为空的记录,也会触发相同的空引用报错
    同时你的原有代码还存在逻辑漏洞:重复校验仅弹出提示,不会终止后续提交流程,就算检测到重复还是会插入新记录,其余字段校验逻辑也存在取值错误的问题。
修复步骤
  • 首先关闭DataGridView的用户手动添加行开关,消除无意义的空白行
  • 调整重复校验逻辑,增加空值判断,检测到重复后直接终止提交
  • 修复字段校验的取值错误、判断逻辑错误问题
修复后代码
// 无用的全局变量可直接删除
// int value = 0;

private void frmUsers_Load(object sender, EventArgs e)
{
    // 关闭用户手动添加行,避免空白行导致空引用
    dgvUsers.AllowUserToAddRows = false;
}

private void btnSubmit_Click(object sender, EventArgs e)
{            
    // 重复名校验
    for (int item=0; item < dgvUsers.Rows.Count;item++)
    {
        var cellValue = dgvUsers.Rows[item].Cells[0].Value;
        // 先判断单元格值不为空再做比较,同时去除前后空格避免误判
        if (cellValue != null && txtFName.Text.Trim() == cellValue.ToString().Trim())
        {
            MessageBox.Show("Duplicate Name from Previous Account");
            // 检测到重复直接终止后续逻辑
            return;
        }
    }

    // 修复字段校验的取值错误,均取Text属性获取用户输入
    bool fname_contains = txtFName.Text.Any(char.IsDigit);
    bool lname_contains = txtLName.Text.Any(char.IsDigit);
    // 修复年龄判断逻辑:只要存在非数字字符就判定非法
    bool age_contains = txtAge.Text.Any(x => !char.IsDigit(x));
    string[] value = { txtFName.Text.Trim(), txtLName.Text.Trim(), txtAge.Text.Trim() };

    if (value.Distinct().Count() != value.Length)
    {
        MessageBox.Show("Your Provided Names Are Duplicates", "Processing Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }

    if (fname_contains || lname_contains)
    {
        MessageBox.Show("Your Name Cannot Include Any Digits!", "Processing Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }

    if (age_contains)
    {
        MessageBox.Show("Your Age Cannot Include Any Letters!", "Processing Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }

    // 所有校验通过再添加行
    dgvUsers.Rows.Add(value);
    MessageBox.Show("Process Completed", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:54:03