Commiting changes in DataGridView before Row Chang

2019-08-08 10:04发布

问题:

We're working with a DataGridView bound to a database. We are trying to have one of the columns calculated as an average of some of the other columns from the database.

    • We were unable to create a computed column in the database nor were we successful in creating one in the dataset. If there's a way to do this, our problem is solved.

Ex: AvgSkill = Avg(Skill1, Skill2, Skill3)

  1. Since we can't seem to create a computed column, we tried creating a cell event handler that would calculate the new average and then update the database with the new information, however as soon as we change a cell, and try to update the database, we lose all the data we added to that row.

We've figured out that the dataGridView only updates the bound data source when you leave the row, so when we try to do an update, it erases anything entered in that row.

Is there a way to force the datagridview to update the bound data source in our event handler before we leave the row? Updating the tableadapter doesn't seem to do it.

thanks in advance for any help :)

-Dominique

回答1:

I think you want to do the following in the cell change event handler:

    private void dgvPlayers_CellValidated(object sender, DataGridViewCellEventArgs e)
    {
         this.Validate();
    }

Forces the validation of the DataGridView with every cell change. You could limit this action to specific columns by checking e.ColumnIndex. You could also include any code required to make calculations at the same time.

;)