Click here to Skip to main content
14,773,203 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

I am trying to Change the Back color of a Cell in a Datagridview if the Column value >39. I am using below code ,

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // If the column is the Artist column, check the
            // value.
            if (this.dataGridView1.Columns[e.ColumnIndex].Name == "SensorValue")
            {
                if (e.Value != null)
                {
                    // Check for the string "pink" in the cell.
                    string stringValue = (string)e.Value;
                    stringValue = stringValue.ToLower();
                    if ((stringValue.IndexOf("pink") > 39))
                    {
                        e.CellStyle.BackColor = Color.Pink;
                    }

                }
            }
        }




Its not working. I got no error but color do not change.
Posted

change this line(string stringValue = (string)e.Value;)
to
(string stringValue = e.Value.ToString();)
   
check this code

private void datagridview_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
       if (Convert.ToString(datagridview[e.Columnindex,e.RowIndex].value)=="somevalue")
                    datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red;


} 
   
Hi,

try this code :

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (GridViewRow Line in dataGridView1.Rows)
  {
     if (MaLigne.RowType == DataControlRowType.DataRow)
     {
         if (this.dataGridView1.Columns[e.ColumnIndex].Name == "SensorValue")
         {
          if (Convert.ToInt32(dataGridView1.Rows[Line.RowIndex] > 39)
             {
              dataGridView1.Rows[Line.RowIndex].BackColor = System.Drawing.Color.LightBlue;

             }
          }
     }
  }
}
   
sorry it is not "MaLigne" but "line"
   

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