Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Iterate Over DataGridView & Change Row Color

Tags:

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;             }         } 
like image 552
Goober Avatar asked Jul 03 '09 10:07

Goober


1 Answers

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;                 }             }         }     } 
like image 126
TheVillageIdiot Avatar answered Sep 22 '22 22:09

TheVillageIdiot