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

基于DataGridView单元格空值的C#循环实现问题求助

C# DataGridView遍历处理方案

核心问题解决

  1. 循环终止条件:填dataGridView2.Rows.Count,这是DataGridView的总行数,确保遍历所有行。
  2. 单元格空值判断:需要先检查单元格值是否为null,再判断转字符串后是否为空(含空白字符),避免空引用异常,条件为dataGridView2.Rows[i].Cells[5].Value == null || string.IsNullOrWhiteSpace(dataGridView2.Rows[i].Cells[5].Value.ToString())

完整代码(含健壮性优化)

for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
    var cell5Value = dataGridView2.Rows[i].Cells[5].Value;
    // 判断第5列值是否为null或空/空白字符
    if (cell5Value == null || string.IsNullOrWhiteSpace(cell5Value.ToString()))
    {
        // 处理其他单元格可能为null的情况,避免ToString()报错
        TxtSayKod.Text = $"{dataGridView2.Rows[i].Cells[2].Value?.ToString() ?? ""}{dataGridView2.Rows[i].Cells[10].Value?.ToString() ?? ""}";
        TxtHome.Text = dataGridView2.Rows[i].Cells[3].Value?.ToString() ?? "";
        TxtAway.Text = dataGridView2.Rows[i].Cells[10].Value?.ToString() ?? "";
        
        button1.PerformClick();
        Thread.Sleep(3000);
        btnupdate.PerformClick();                    
    }
    // 单元格有值时,for循环自动执行i++,直接进入下一行遍历
}

关键说明

  • string.IsNullOrWhiteSpace:同时覆盖空字符串、null、全空白字符的判断场景,比单纯判断""更全面
  • ?.ToString() ?? "":当单元格值为null时,不会抛出空引用异常,自动替换为空字符串,提升代码健壮性
  • 无需额外写跳转逻辑:for循环本身会在每次迭代后执行i++,单元格有值时直接进入下一次循环即可

内容的提问来源于stack exchange,提问作者Suat Seçkin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:01:04