简体   繁体   中英

Winforms DataGridView CellValidating and CellValueChanged

I have a DataGridView with BindingList<T> as DataSource . I let user input values into one column and I have a method for calculating other column values depending on the input.

Now when I put my method into CellValueChanged event, value calculates when I leave edited cell.

But, when I put my method into CellValidating event, value calculates when I leave the next cell. To make it more clear when I press Enter for the second time. If I switch to another control right after editing a cell, my method isn't executed at all.

I did some testing. I've added TryParse with message box after my method in CellValidating . Message box shows immediately when I try to leave a cell, still calculation runs when I leave the next cell (second Enter).

Why is this happening? What can this be caused by?

Edit

flightDataGridView.DataSource = flight.Ships;
BindingList<Ship> _ships = new BindingList<Ship>();

_ships.Add(new Ship([some stuff here]));
.
.


public void UpdateCargoCapacity()
        {
            foreach (Ship ship in _ships)
            {
                ship.CargoCapacity = ship.SingleCargoCapacity * ship.Quantity;
            }
            flightDataGridView.Refresh();
        }

private void flightDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            flight.UpdateCargoCapacity();
            if (e.ColumnIndex == 1)
            {
                int i;
                if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
                {
                    e.Cancel = true;
                    MessageBox.Show("Incorrect input", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

I've thought about it and the reason of this working that way is really simple. When CellValidating is fired the cell still has old value. Then value is updated. Then when next cell is being validated, calculation method is executed again and previous cell's new value is used for calculation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM