Click here to Skip to main content
12,069,894 members (66,184 online)
Rate this:
 
Please Sign up or sign in to vote.
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 8-Mar-13 1:47am
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

change this line(string stringValue = (string)e.Value;)
to
(string stringValue = e.Value.ToString();)
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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;
 

} 
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

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;
 
             }
          }
     }
  }
}
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 4

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

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web04 | 2.8.160208.1 | Last Updated 8 Mar 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100