Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I retrieve the previous value of a DataGridView cell using the CellValueChanged event?

I am writing a C# application that uses a DataGridView and I would like to validate the input each time a user changes the data that's there.

I began by using the CellValidating event which has a really nice CancelEdit() method that will return the cell to its previous value. However, this event is fired every time the user leaves the cell, regardless of whether or not it has changed.

Does CellValueChanged support a sort of cancel or rollback method to the previous value? This way I would be able to still validate the data, but not waste time with cells that didn't need it, but would prefer not to sacrifice the ability to restore the cell if data is invalid.

Here is a bit of code:

private void dataGrid1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if(dataGrid1.Columns[e.ColumnIndex].Name == "dateColumn")
    {
        String input = e.FormattedValue.ToString();

        // Split the date from MM/DD/YYYY format
        String[] temps = input.Split('/');
        try
        {
            if(temps[2].Length != 4)
                MessageBox.Show("The year entered is not the correct length.", "Invalid Year", MessageBoxButtons.OK);

            DateTime date = new DateTime(Convert.ToInt32(temps[2]), Convert.ToInt32(temps[0]), Convert.ToInt32(temps[1]));
        }
        catch (Exception ex) // If exception is thrown, date was invalid
        {
            MessageBox.Show("The date entered was invalid.", "Invalid date", MessageBoxButtons.OK);
            dataGrid1.CancelEdit(); // Set cell value back to what it was prior to user's change
            e.Cancel = true; // Have focus stays with this cell rather than move down a row.
        }
    }
}
like image 931
AdamMc331 Avatar asked Jul 11 '14 16:07

AdamMc331


1 Answers

You could try another aproach like this:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    newvalue = (int)dataGridView1[e.ColumnIndex, e.RowIndex].Value;
}

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
    oldvalue = (int)dataGridView1[e.ColumnIndex, e.RowIndex].Value;
}

Assuming its an int,if its another datatype then will also work(except offcourse the variables oldvalue and newvalue must be that type also).

Or by your question,its just about the old value,then you will only need the CellBeginEdit event and then use the oldvalue variable inside the validating event.

like image 144
terrybozzio Avatar answered Sep 17 '22 20:09

terrybozzio