Agasi Mkhitaryan
Agasi Mkhitaryan

Reputation: 180

How to change datagrid cell value when user leaves cell

Can't find any way to do what i what. I have a DataGridView named data1. All i want is to check if current cell is acceptable(not lower than -99) after we fill it. And if it is - change it to -99. Similar if i set minimum to a textbox and change its value if it's not correct. Here is the code:

private void data1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    if (Convert.ToInt32(((DataGridView)sender).CurrentCell.Value) < -99)
    {
        ((DataGridView)sender).CurrentCell.Value = -99;                
    }
}

This code does not work. And no errors appeared.

Upvotes: 1

Views: 2962

Answers (2)

Agasi Mkhitaryan
Agasi Mkhitaryan

Reputation: 180

This code works as you want it to:

private void data1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewTextBoxCell cell = (DataGridViewTextBoxCell)data1.Rows[e.RowIndex].Cells[e.ColumnIndex];
    if (Convert.ToInt32(cell.Value) <= -99)
        cell.Value = -99;
}

Cellleave Event gets previous value of the cell after you have changed it to a different one and left the cell. And CellEndEdit Event gets the last value. The code works the same also in CellValidated Event.

Upvotes: 2

BenCamps
BenCamps

Reputation: 1844

I think what you are looking for is DataGridView.CellValidating this event fires when the user is leaving the current cell but before CellLeave fires or bound data gets pushed to the datasource. This allows you to: check the value the user entered, prevent the user from leaving the cell, change the value the user entered, set an error indicator on the cell.

Upvotes: 1

Related Questions