HiSura
HiSura

Reputation: 142

C# Windows Form - How to get previous/old value of cell

I have a Datagridview. I'm trying to get the old value (value before edit) and the new value, then compare.

private void GridDetails_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (e.ColumnIndex == GridDetails.Columns["Address"].Index)
        {
            var oldValue = GridDetails[e.ColumnIndex, e.RowIndex].Value;
            var newValue = GridDetails[e.ColumnIndex, e.RowIndex].EditedFormattedValue;

            if(oldValue!=newValue)
            {
                GridDetails.Rows[e.RowIndex].Cells["Address"].Style.BackColor = Color.FromArgb(212, 212, 155);
            }

        }
    }

But Both old and new values are the same.

Upvotes: 0

Views: 551

Answers (2)

HiSura
HiSura

Reputation: 142

Chamod, you are right. I used CellBeginEdit and CellEndEdit, and it worked. Below is my answer.

string oldValue;
private void GridDetails_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
        oldValue = GridDetails[e.ColumnIndex, e.RowIndex].Value.ToString();
}


private void GridDetails_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex == GridDetails.Columns["Address"].Index)
    {
       
        string newValue = e.FormattedValue.ToString();

        if(oldValue!=newValue)
        {
            GridDetails.Rows[e.RowIndex].Cells["Address"].Style.BackColor = Color.FromArgb(212, 212, 155);
        }

    }
}

Upvotes: 1

chamod priyamal
chamod priyamal

Reputation: 36

You Can use CellBeginEdit Event of the DataGrid and store the value somewhere Then use CellEndEdit to Compare the new Value with the old value.

Upvotes: 1

Related Questions