如何根据新单元格值是否 > 或 < than current/old cell value? Is there an event which passes the new value before the current is changed, so I can compare them?
更改 DataGridView 单元格前景色数据是从底层源更新的,并且可能被BindingSource绑定。
我遇到了类似的问题。我通过使用
CellValidating
事件来解决这个问题:
void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
var oldValue = dgv[e.ColumnIndex, e.RowIndex].Value;
var newValue = e.FormattedValue;
}
不可否认,我只需要访问旧值,不需要执行任何格式化。不过,我确信您可以通过此事件处理程序应用格式。
如果 DataGridView 控件的内部源是 DataTable,那么您可以使用 DataRowVersion 枚举来使用旧版本的 DataRow。请注意,我已经使用了 CellFormatting 事件。
示例:
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;
}
}
}
您可能想查看
DataGridView.CellValueChanged
事件 (http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx)。
如果您想在保存之前检查该值,请查看
DataGridView.CurrentCellDirtyStateChanged
(http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcelldirtystatechanged.aspx)。
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
...
}
您可以将单元格的旧值存储在变量中,以根据结果进行比较和更改前景色,然后从变量中删除旧值。
问候。
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());
}