C# 在c中为Datagridview行着色时出错#

C# 在c中为Datagridview行着色时出错#,c#,winforms,datagridview,C#,Winforms,Datagridview,我有一个datageidview,它应该使用包含特定值的行来着色 private void dataGridView2_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { foreach (DataGridViewRow myrow in dataGridView2.Rows) { if (e.RowIndex != -1)

我有一个datageidview,它应该使用包含特定值的行来着色

    private void dataGridView2_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        foreach (DataGridViewRow myrow in dataGridView2.Rows)
        {
            if (e.RowIndex != -1)
            {
                    if (myrow.Cells[7].Value.ToString() == "Error")
                    {
                        myrow.DefaultCellStyle.BackColor = Color.Red;
                    }
                    else if (myrow.Cells[7].Value.ToString() == "NoError")
                    {
                        myrow.DefaultCellStyle.BackColor = Color.Green;
                    }
                }
        }
    }
但是我有一个问题,当第一行包含这个值时,所有的行都用它的颜色着色


任何帮助???

将为网格中的所有可见单元格发送CellFormatting事件。使用事件中提供的数据更改颜色可能会更幸运

private void dataGridView2_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.RowIndex != -1)
    {
        if (dataGridView2.Rows[e.RowIndex].Cells[7].Value.ToString() == "Error")
        {
            e.CellStyle.BackColor = Color.Red;
        }
        else if (dataGridView2.Rows[e.RowIndex].Cells[7].Value.ToString() == "NoError")
        {
             e.CellStyle.BackColor = Color.Green;
        }
    }
}

如果单元格7的值是错误的,并且我在datagridview_CellFormating中使用此代码,则假设将行设置为红色。这很好,但我想将整行着色。没有单元格。代码中有任何更改??