C# 比较DataGridView单元格中的新旧值
如何根据新单元格值是>还是<当前/旧单元格值来更改DataGridView单元格前景色?在更改当前值之前是否有传递新值的事件,以便我可以比较它们C# 比较DataGridView单元格中的新旧值,c#,.net,datagridview,C#,.net,Datagridview,如何根据新单元格值是>还是
数据从基础源更新,并且可能由BindingSource绑定 您可以将单元格的旧值存储在变量中,根据结果比较和更改前景色,然后从变量中删除旧值
注意。如果DataGridView控件的内部源是DataTable,则可以使用DataRowVersion enum使用旧版本的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).我遇到了类似的问题。我通过使用CellValidating
事件来解决这个问题:
void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
var oldValue = dgv[e.ColumnIndex, e.RowIndex].Value;
var newValue = e.FormattedValue;
}
诚然,我只需要访问旧值,不需要执行任何格式化。不过,我相信您可以通过此事件处理程序应用格式设置。我希望避免这种情况,因为我需要很多列,但如果没有更简单的方法。。。