Reputation: 5529
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.
Upvotes: 16
Views: 37268
Reputation: 1
var cell = ((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell.Value != e.FormattedValue)
{
// Current cell value: cell.Value
// New cell value: e.FormattedValue
// ...
}
Upvotes: 0
Reputation: 1
private double CuerrLineQty;
private void GridTransaction_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (currOp != CurrentOperation.FillDone)
return;
CuerrLineQty = double.Parse(GridTransaction.Rows[e.RowIndex].Cells["DisplayQty"].Value.ToString());
CuerrLineQty = double.Parse(GridTransaction.Rows[e.RowIndex].Cells["DisplayQty"].FormattedValue.ToString());
CuerrLineQty = double.Parse(GridTransaction.Rows[e.RowIndex].Cells["DisplayQty"].EditedFormattedValue.ToString());
}
Upvotes: -1
Reputation: 2581
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.
Upvotes: 27
Reputation: 335
You may want to look at the DataGridView.CellValueChanged
event (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).
Upvotes: 0
Reputation: 1147
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;
}
}
}
Upvotes: 0
Reputation: 765
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.
Upvotes: -1