Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, Below code highlight the entire row, but i need to highlight only specific CELL.






C#
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            int colIndex = e.ColumnIndex;
            int rowIndex = e.RowIndex;


            if (rowIndex >= 0 && colIndex >= 0)
            {
                DataGridViewRow theRow = dataGridView1.Rows[rowIndex];

                if (theRow.Cells[colIndex].Value !=null)
                {
                    if (theRow.Cells[colIndex].Value.ToString() == "Normal")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.Green;
                        theRow.DefaultCellStyle.ForeColor = Color.White;
                        theRow.DataGridView.DefaultCellStyle.Font = new Font("Calibri", 10);

                    }


                else if (theRow.Cells[colIndex].Value.ToString() == "Critical")
                {
                    theRow.DefaultCellStyle.BackColor = Color.Tomato;
                    theRow.DefaultCellStyle.ForeColor = Color.White;

                }

                    else if (theRow.Cells[colIndex].Value.ToString() == "Very Critical")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.DarkRed;
                        theRow.DefaultCellStyle.ForeColor = Color.White;

                   }

                }
Posted
Updated 12-Mar-13 19:20pm
v2

1 solution

First off, that test will never work:
C#
theRow.Cells[colIndex].Value.Equals(null)
Translates to:
C#
Object o;
o.Equals(null)
If the object being tested is null, then there is by definition no instance to call the Equals method on, and since it cannot be static, a null value will always throw an execption, before it can try to test for a null value!

You could try with:
C#
theRow.Cells[colIndex].Value == null
Which stands a better chance of working!
 
Share this answer
 
Comments
Sharp Robin 12-Mar-13 17:28pm    
The right way to do things. I was going to write the same answer. Vote for this.
ontheline89 13-Mar-13 0:21am    
Thank you so much for your reply.
OriginalGriff 13-Mar-13 3:39am    
You're welcome!
ontheline89 13-Mar-13 1:18am    
One thing more i wanted to ask that, above code highlight Entire Row, how can i highlight only specific CELL ?? Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900