比较DataGridView单元格中的旧值和新值
如何根据新单元格值是>还是<比当前/旧单元格值更改DataGridView单元格ForeColor? 是否有一个事件在更改电流之前传递新值,所以我可以比较它们?
数据从底层源更新,可能受BindingSource约束。
我遇到了类似的问题。 我通过使用CellValidating
事件来解决这个问题:
void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { var oldValue = dgv[e.ColumnIndex, e.RowIndex].Value; var newValue = e.FormattedValue; }
不可否认,我只需要访问旧值,我不需要执行任何格式化。 不过,我确信您可以通过此事件处理程序应用格式。
您可以将单元格的旧值存储在变量中,以根据结果比较和更改ForeColor,然后从变量中删除旧值。
问候。
如果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)。