john john - 1 month ago 18
C# Question

DataGridView ComboBox Column: Change cell value after selection from dropdown is made?

I have setup a ComboBoxColumn for my DataGridView and set its selectable values from an enumeration. It mostly works as I would like with the following exception.

Whenever I click the dropdown arrow and then select one of the enum values, it remains in sort of a "intermediate" state where the CellValueChanged event isn't triggered. I need to focus on another cell or another control for the event to fire.

I also have an event handler for the DataGridView's Leaving event which "validates" the contents by making sure that no cell is empty.

So, if I create a row and fill all the cells and come to the (currently blank) ComboBox column, change it to a value, and then click a Run button; my error dialog pops up because the ComboBox selection wasn't "saved".

How can I get around this? Is there a way that after I select a value from the drop down it automatically "sets" the value?

Thanks!

Answer

You should use CurrentCellDirtyStateChanged event and force a commit edit on the grid:

    private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }

Hope it helps!

Comments