Devrok
Devrok

Reputation: 37

How to force DataGridView cell validation before closing form?

I have a DataGridView that I can edit. After editing, and when I click Enter or select another cell, CellValueChanged event occurs and I save this new value.

My problem : If I change cell value and close form without click Enter or select another cell before, this last value isn't saved.

Is there a way to solve that ?

Upvotes: 2

Views: 2729

Answers (3)

matt.dolfin
matt.dolfin

Reputation: 672

grid.EndEdit() worked for me in the form closing event.

Upvotes: 0

Reza Aghaei
Reza Aghaei

Reputation: 125197

Assuming you have a DataTable as DataSource of your DataGridView, then use the following code to validate and end edit:

this.Validate();
dataGridView1.BindingContext[yourDatTable].EndCurrentEdit();

Upvotes: 2

Nemanja Vidačković
Nemanja Vidačković

Reputation: 73

Check first how the "CellValueChanged" event works. i think in you case when you close the form the event isnt triggered. What i would do is when you close Form the event "FormClosing" is triggered and it calls a method("SaveThisNewValue()") that saves your value. The method for saving your values is also used in "cellValueChanged" event

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        SaveThisNewValue();
    }

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        SaveThisNewValue();
    }

    private void SaveThisNewValue()
    {
        //saves the cell value
    }

Upvotes: 0

Related Questions