0

I'm using dataGridView in Windows Forms to show the database and want to color it. If [Solver] column is NULL it should paint LightSalmon, else LightGreen. However even if the column value is NULL it still see it as not null and paint into LightGreen.

This is my table:
      [Id]
      [Employee]
      [Section]
      [Machine]
      [Station]
      [MachNo]
      [Area]
      [Type]
      [Desc]
      [Recommendation]
      [Date]
      [Solver]
      [Process]


public void Color()
{
    for(int i = 0; i< dataGridView1.Rows.Count; i++)
        if (DBNull.Value.Equals(dataGridView1.Rows[11]))
        {
            dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightSalmon;
        }
        else
        {
            dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
        }   
}
2
  • GRidView.Column datatype is not same to DBNull Commented Sep 27, 2019 at 8:55
  • Also try implementing dataGridView1.Refresh(). Commented Sep 27, 2019 at 8:57

4 Answers 4

1

[Solver] (11th column) is a column not a row, so you need to check that column of each row is null or not

public void Color()
{
    for(int i = 0; i< dataGridView1.Rows.Count; i++)
    {
        if (dataGridView1.Rows[i].Cells[11].Value == null || dataGridView1.Rows[i].Cells[11].Value == DBNull.Value)
        {
             dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightSalmon;
        }    
        else
        {
            dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Rather use the Cells property on that row like

if (DBNull.Value.Equals(dataGridView1.Rows.Cells[11].Value))

Comments

0

You can use like below

dataGridView1.Rows[i].DefaultCellStyle.BackColor = dataGridView1.Rows[i].Cells[11].Value == null ? 
                                                          Color.LightSalmon : Color.LightGreen

or

dataGridView1.Rows[i].DefaultCellStyle.BackColor = dataGridView1.Rows[i].Cells[11].Value == DBNull.Value ? 
                                                  Color.LightSalmon : Color.LightGreen

Comments

0
for(int i = 0; i< dataGridView1.Rows.Count; i++)
    {  
        if (dataGridView1.Rows[i].Cells[11].Value == null || 
        dataGridView1.Rows[i].Cells[11].Value == DBNull.Value)
    {
         dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
    }    
    else
    {
        dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.