C# Iterate Over DataGridView & Change Row Color

Goober picture Goober · Jul 3, 2009 · Viewed 60.5k times · Source

I have a datagridview made up of multiple rows and columns. I want to iterate through each row and check the contents of a specific column. If that column contains the word "NO", I want to change the forecolor of the entire row to Red. Here is an attempt at some code so far but It's certainly not working, starting to wonder If I need to iterate over every cell?

CODE:

foreach (DataGridViewRow dgvr in dataGridView1.Rows)
        {
            if (dgvr.Cells["FollowedUp"].Value.ToString() == ("No"))
            {
                dgvr.DefaultCellStyle.ForeColor = Color.Red;
            }
        }

Answer

TheVillageIdiot picture TheVillageIdiot · Jul 3, 2009

hook up OnRowDataBound event then do stuff

ASPX (Grid):

    <asp:.... OnRowDataBound="RowDataBound"..../>

Code Behind:

    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex == -1)
        {
            return;
        }

        if(e.Row.Cells[YOUR_COLUMN_INDEX].Text=="NO"){
             e.Row.BackColor=Color.Red;   
        }
    }

FOR WinForms:

hook the **DataBindingComplete** event and do stuff in it:

     private void dataGridView1_DataBindingComplete(object sender, 
                       DataGridViewBindingCompleteEventArgs e)
    {
        if (e.ListChangedType != ListChangedType.ItemDeleted)
        {
            DataGridViewCellStyle red = dataGridView1.DefaultCellStyle.Clone();
            red.BackColor=Color.Red;

            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                if (r.Cells["FollowedUp"].Value.ToString()
                       .ToUpper().Contains("NO"))
                {
                    r.DefaultCellStyle = red;
                }
            }
        }
    }