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

如何在C#中仅遍历DataGridView的单列?

只遍历DataGridView指定列的解决方法

你当前的嵌套foreach会遍历每一行的所有单元格,所以才会输出两列的内容。要只遍历其中一列,直接定位到目标列的单元格就好,给你两种常用的实现方式:

1. 通过列索引获取目标单元格

如果知道目标列的索引(比如第一列索引是0,第二列是1),可以直接通过索引访问:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    // 跳过DataGridView默认的空白新行,避免空值异常
    if (!row.IsNewRow)
    {
        // 这里指定要遍历的列索引,比如0就是第一列
        DataGridViewCell targetCell = row.Cells[0];
        // 先判断单元格值不为null,再转换为字符串
        if (targetCell.Value != null)
        {
            MessageBox.Show(targetCell.Value.ToString());
        }
    }
}

2. 通过列名获取目标单元格

如果列名是固定的,用列名访问会更健壮(就算后续调整列的顺序,代码也不用修改):

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (!row.IsNewRow)
    {
        // 替换成你实际的列名,比如"Name"或者"ID"
        DataGridViewCell targetCell = row.Cells["YourColumnName"];
        if (targetCell.Value != null)
        {
            MessageBox.Show(targetCell.Value.ToString());
        }
    }
}

额外小技巧:用for循环遍历(可选)

如果你习惯用for循环,也可以这样写,效果是一样的:

// 减1是为了跳过最后一行的空白新行
for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count - 1; rowIndex++)
{
    DataGridViewCell targetCell = dataGridView1.Rows[rowIndex].Cells[0];
    if (targetCell.Value != null)
    {
        MessageBox.Show(targetCell.Value.ToString());
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:49:46