Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I've created a dgv with a hidden column. If there is a value in that column, I want to turn the background of cell[3] on that row to blue. The closest I've come is turning the whole column blue. Where am I going wrong. Here's the code. TIA.

for (int i = 0; i < dgvSODetail.Rows.Count; ++i)
           {
               if (dgvSODetail.Rows[i].Cells["Notes"].Value!=null)
               {
                   dgvSODetail.Rows[i].Cells[3].Style.BackColor = Color.Blue;
               }
               else
               {
                   dgvSODetail.Rows[i].Cells[3].Style.BackColor = Color.White;
               }
           }


What I have tried:

I tried using every instance of Cells I could find but this is the closest I get.
Posted
Updated 25-Jan-19 7:26am
Comments
Richard MacCutchan 25-Jan-19 12:15pm    
You forgot to tell us what happens when you run this code.
Damian Jones 25-Jan-19 12:49pm    
When I run the code I get a full column of blue instead of just the cell in that column.
Richard MacCutchan 25-Jan-19 13:01pm    
I just tried it and it works fine for me. I suggest you use your debugger and find out what is happening.
raddevus 25-Jan-19 13:25pm    
You get a full column of blue because it iterates through every row in the datagridview and sets it blue : dgvSODetail.Rows[i].Cells[3].Style.BackColor = Color.Blue

Rows[i].Cells[3] is every row since i changes.

See here: Colouring DataGridView Cells According to their Content in WinForms[^] - it doesn't do exactly what you want, but all you have to do is reference the right column instead of the current.
 
Share this answer
 
Got by just grinding it out.... Used Console.Writeline to help me see what was going on:

for (int i = 0; i < dgvSODetail.Rows.Count; ++i)
            {
                if (dgvSODetail.Rows[i].Cells["Notes"].Value != null)
                {
                    if (dgvSODetail.Rows[i].Cells["Notes"].Value.ToString().Length > 0)
                    {
                        Console.WriteLine(dgvSODetail.Rows[i].Cells["Notes"].Value.ToString());

                        dgvSODetail.Rows[i].Cells[3].Style.BackColor = Color.Blue;
                    }
                }
                else
                {
                    dgvSODetail.Rows[i].Cells[3].Style.BackColor = Color.White;
                }
 
Share this answer
 

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