Im trying to change the color of a row when the value of one of my columns is changed to Terminated .

for example when an employee is termiated i want the color of his record to be red.

this is the code i have so far.

foreach (DataRow dr in dt.Rows)
            {
               if (dr[9].ToString() == "Terminated")
                {
                    dataGridView5.BackgroundColor = Color.Blue;
                }

            }

Edited 6 Years Ago by NH1: n/a

no idea if this is how, and am just thinking about it in my head but

shouldn't the line be

dr.BackgroundColor = Color.Blue;

since dr is the row you are working on.

Comments
Good observation.

I think you guys may be confusing DataGridViewRows with DataRows. Datatables don't store formatting information because they aren't directly displayed. You need to set the background colour of the DataGridView's Row.
I'd suggest looking at the CellFormatting event as it is only called against cells that are to be displayed. If you have a datagridview thats big enough to display ten rows at a time but has 100's or 1000's of rows in it then you only want to change the appearance of rows that are currently visible; looping through every single row could cause your program to freeze momentarily.
In the CellFormatting event, check the value of the status column and set the row's .DefaultCellStyle.BackColor property accordingly:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (dataGridView1.Rows[e.RowIndex] == null || dataGridView1.Rows[e.RowIndex].IsNewRow)
            return;

        if (dataGridView1["Status", e.RowIndex].Value != null && dataGridView1["Status", e.RowIndex].Value.ToString() == "Terminated")
        {
            dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
        }
        else
        {
            dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = DefaultBackColor;
        }
    }
Comments
:)

Yes that is true,but I was trying to highlight the problem with "foreach" statement. :)

public static int Main( )
    {
        DrawingObject[] dObj = new DrawingObject[4];

        dObj[0] = new Line();
        dObj[1] = new Circle();
        dObj[2] = new Square();
        dObj[3] = new DrawingObject();

        foreach (DrawingObject drawObj in dObj)//This statement.......
        {
            drawObj.Draw();
        }

        return 0;
    }

Edited 6 Years Ago by Software guy: n/a

@BrianMill1999, this is the C# board. The OP has not given any indication that his problem is ASP.NET related. If it is, then you are correct and this thread needs to be moved to the correct forum.

This article has been dead for over six months. Start a new discussion instead.