Link to home
Create AccountLog in
Avatar of frtools
frtoolsFlag for United States of America

asked on

Change Background Color of Datagridview Row Based on Column

Is there a gridview event or a way programatically to change the background color of a row when a column in a row meets certain criteria.

I have a List of String[] arrays that are added to a datatable then bound to a gridview.

private void FillTable()
        {
           
           
            if (listTable.Rows.Count == 0)
            {
                DeclareTableColums();
            }
            else if (tableclear == 1)
            {
                listTable.Clear();
            }

            foreach (string[] item in ItemList)
            {
                    listTable.Rows.Add(item[0], item[1], item[2], item[3]);
            }
 
            listTable.AcceptChanges();
            dataGridView1.DataSource = listTable;

           
        }
Avatar of trestan
trestan
Flag of Canada image

You can set the background color of a cell like this:

this.dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Gold;

Add your own cretiria check before that.

Is this what you want to know?
Avatar of frtools

ASKER

I thought there was an event handler in a gridview for when a row was added you could check values of a cell.
If the cell met certain criteria I wanted to change the background color of the entire row not just that individual cell.
Avatar of frtools

ASKER


This was how I was going to try it -- error when executed "Object reference not set to an instance of an object."

for (int x = 0; x <= dataGridView1.RowCount; x++)
            {
                if (Int32.Parse(this.dataGridView1.Rows[x].Cells[1].Value.ToString()) > 1)
                {
                    this.dataGridView1.Rows[x].DefaultCellStyle.BackColor = Color.Olive;
                    this.dataGridView1.Rows[x].DefaultCellStyle.Font = font;
                }
            }
ASKER CERTIFIED SOLUTION
Avatar of frtools
frtools
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of frtools

ASKER

Worked out my own question.