如何在 C# 中检查 DataGridView 中的行颜色

本文关键字:颜色 DataGridView 检查 | 更新日期: 2023-09-27 18:35:23

我想在 C# 中获取DataGridView行颜色。

我像这样设置了一行的背景颜色:

dgvGrid.Rows[rowIndex].DefaultCellStyle.BackColor = Color.LightPink;

现在我只想获取那些BackgroundColor LightPink的行。

foreach (DataRow dr in dgvGrid.Rows)
{
    if( /* get the row whose color is pink */)
    {
    }
}

如何在 C# 中检查 DataGridView 中的行颜色

你很接近。但是,请注意,dgvGrid.Rows不是DataRow的集合 - 它:

表示数据表中的一行数据。

相反,它是一个DataGridViewRowCollection

DataGridViewRow 对象的集合。

在循环中修复此问题后,只需按照与设置相同的方式检查行颜色:

foreach (DataGridViewRow row in dgvGrid.Rows)
{
    if (row.DefaultCellStyle.BackColor == Color.LightPink)
    {
        // your code here
    }
}

像这样:

int index = 0;
foreach (var item in ListGV.Rows)
{        
    if (ListGV.Rows[index].BackColor == Color.Pink)                
    {
    }
    index++;
}