user6894907 user6894907 - 2 months ago 19
C# Question

If DataGridView cell value bigger than another cell

Hi i want to compare two cells, both of them with number value.
If Cell1 is bigger than cell2 the color cell to be green.

Here is my code: In Cell Formating in datagridview

foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (row.Cells[3].Value.ToString() > (row.Cells[4].Value.ToString()))
{
row.Cells[3].BackColor = Color.PaleGreen;
}


But i get two errors:In first line Operator '>' cannot be applied to operands of type 'string' and 'string' and in second line System.Windows.Forms.DataGridViewCell' does not contain a definition for 'BackColor' and no extension method 'BackColor' accepting a first argument of type 'System.Windows.Forms.DataGridViewCell' could be found

Answer

Both of those errors are valid. You're casting the cell values to strings, but if you want to compare as numbers then you need to make them numbers. Also the BackColor is in the cell's style property. So your code should look more like this:

foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
    double value1;
    double value2;
    if(!double.TryParse(row.Cells[3].Value.ToString(), out value1) || !double.TryParse(row.Cells[4].Value.ToString(), out value2))
    {
        // throw exception or other handling here for unexcepted values in cells
    }
    else if (value1 >  value2)
    {
        row.Cells[3].Style.BackColor = Color.PaleGreen;
    }