views:

14

answers:

1

I have a windows forms DataGridView that contains some DataGridViewComboBoxCells that are bound to a source collection using DataSource, DisplayMember and ValueMember properties. Currently the the combobox cell commits the changes (i.e. DataGridView.CellValueChanged is raised) only after I click on another cell and the combobox cell loses focus.

How would I ideally commit the change directly after a new value was selected in the combobox.

+1  A: 

This behaviour is written into the implementation of the DataGridViewComboBoxEditingControl. Thankfully, it can be overridden. First, you must create a subclass of the aforementioned editing control, overriding the OnSelectedIndexChanged method:

protected override void OnSelectedIndexChanged(EventArgs e) {
    base.OnSelectedIndexChanged(e);

    EditingControlValueChanged = true;
    EditingControlDataGridView.NotifyCurrentCellDirty(true);
    EditingControlDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

This will ensure that the DataGridView is properly notified of the change in item selection in the combo box when it takes place.

You then need to subclass DataGridViewComboBoxCell and override the EditType property to return the editing control subclass from above (e.g. return typeof(MyEditingControl);). This will ensure that the correct editing control is created when the cell goes into edit mode.

Finally, you can set the CellTemplate property of your DataGridViewComboBoxColumn to an instance of the cell subclass (e.g. myDataGridViewColumn.CellTemplate = new MyCell();). This will ensure that the correct type of cell is used for each row in the grid.

Bradley Smith