15
votes

How to change DataGridView cell ForeColor based on whether new cell value is > or < than current/old cell value? Is there an event which passes the new value before the current is changed, so I can compare them?

The data is updated from underlying source, and may be bound by BindingSource.

4

4 Answers

26
votes

I ran into a similar issue. I tackled this by using the CellValidating event instead:

void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    var oldValue = dgv[e.ColumnIndex, e.RowIndex].Value;
    var newValue = e.FormattedValue;
}

Admittedly, I just needed access to the old value, I didn't need to perform any formatting. I'm sure you can apply formatting through this event handler, though.

0
votes

If the inner source of DataGridView control is a DataTable then you can utilize the older version of DataRow using DataRowVersion enum. Note that I have utilized CellFormatting Event.

Example:

private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // if NOT the DataGridView's new row
    if (!this.dataGridView1.Rows[e.RowIndex].IsNewRow)
    {
        // if my desired column
        if (e.ColumnIndex == 0)
        {
            TestDataSet.TestRow row;

            row = (TestDataSet.TestRow)((DataRowView)this.dataGridView1.Rows[e.RowIndex].DataBoundItem).Row;

            if (row.Column1, (int)row["Column1", DataRowVersion.Original]) > 0)
                    e.CellStyle.ForeColor = Color.Red;
        }
    }
}
0
votes

You may want to look at the DataGridView.CellValueChangedevent (http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx).

If you want to check the value before it is saved, then look at DataGridView.CurrentCellDirtyStateChanged (http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcelldirtystatechanged.aspx).

-1
votes

You can store the old value of the cell in a variable, to compare and change the ForeColor depending on the result, then delete the old value from the variable.

Regards.