Compare old and new value in DataGridView cell

前端 未结 4 750
暗喜
暗喜 2021-01-11 11:18

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

相关标签:
4条回答
  • 2021-01-11 11:47

    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 讨论(0)
  • 2021-01-11 11:57

    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).

    0 讨论(0)
  • 2021-01-11 11:58

    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 讨论(0)
  • 2021-01-11 12:04

    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.

    0 讨论(0)
提交回复
热议问题