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

.NET Framework 4.7 WinForm 如何将DataGridView高亮单元格值添加到ListBox

问题根因

你代码中定义的ColorValue属性是未执行求值的IEnumerable<string>类型LINQ迭代器,字符串插值时默认调用了迭代器的ToString()方法,因此输出的是迭代器的类型名而非实际的单元格值。同时你的代码对同一行的单元格做了3次重复遍历,存在冗余性能损耗,也缺少空值防护逻辑。

修复后代码
var foundValues = dataGridView1.Rows.Cast<DataGridViewRow>()
    // 跳过DataGridView自带的空白新增行,避免空引用异常
    .Where(row => !row.IsNewRow)
    .Select(row => 
    {
        // 单次遍历当前行,拿到所有黄色背景单元格的数值
        var yellowCellValues = row.Cells.Cast<DataGridViewCell>()
            // 如果单元格背景色是继承自行/全局样式,把Style替换为InheritedStyle即可
            .Where(c => c.Style.BackColor == Color.Yellow && c.Value != null)
            .Select(c => c.Value.ToString())
            .ToList();
        
        // 取表头为"XX"的列的数值
        var nameColumnIndex = row.Cells.Cast<DataGridViewCell>()
            .First(cell => cell.OwningColumn.HeaderText == "XX")
            .ColumnIndex;
        var nameValue = row.Cells[nameColumnIndex].Value?.ToString() ?? string.Empty;

        return new
        {
            Name = nameValue,
            // 多个黄色单元格值用逗号拼接,无内容时显示空字符串
            ColorValue = string.Join(", ", yellowCellValues),
            Count = yellowCellValues.Count
        };
    })
    .ToArray();

// 先清空原有项避免重复添加
listBox1.Items.Clear();
foreach (var item in foundValues)
{
    listBox1.Items.Add($"{item.Name}, {item.ColorValue}, {item.Count}");
}
额外注意点

如果你的单元格黄色背景是通过DataGridViewRow.DefaultCellStyle或者全局DefaultCellStyle设置的,直接判断cell.Style.BackColor会因为值为Color.Empty导致匹配失败,此时把判断条件中的c.Style.BackColor替换为c.InheritedStyle.BackColor即可正确识别继承的背景色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:15:08