Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

commit changed in DataGridView when selection changed in ComboBox

How can I force the DataGridView.CellValueChanged event to be raised (and have the changed acutally committed to the DataGridViewCell.Value property) as soon as the ComboBox editing control in a cell changed its selection? By default the event is only raised after the cell with the ComboBox loses focus.

like image 740
bitbonk Avatar asked Feb 26 '23 08:02

bitbonk


2 Answers

I solved it doing this:

    myDataGridView.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(myDataGridView_EditingControlShowing);

    private void myDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
        {
            ComboBox cmb = (ComboBox)e.Control;
            cmb.SelectionChangeCommitted -= new EventHandler(cmb_SelectionChangeCommitted);
            cmb.SelectionChangeCommitted += new EventHandler(cmb_SelectionChangeCommitted);
        }
    }

    void cmb_SelectionChangeCommitted(object sender, EventArgs e)
    {
        dgvPresupuesto.CurrentCell.Value = ((DataGridViewComboBoxEditingControl)sender).EditingControlFormattedValue;
    }
like image 170
teteArg Avatar answered Feb 28 '23 08:02

teteArg


I ended up doing it this way. I have no idea if that is the "preferred" way or if it will yield any side effects later, but for now it seems to work:

this.gridView.EditingControlShowing += this.GridViewOnEditingControlShowing;

private void GridViewOnEditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    ComboBox cellComboBox = e.Control as ComboBox;
    if (cellComboBox != null)
    {
        // make sure the handler doen't get registered twice
        cellComboBox.SelectionChangeCommitted -= this.CellComboBoxOnelectionChangeCommitted;
        cellComboBox.SelectionChangeCommitted += this.CellComboBoxOnelectionChangeCommitted;
    }
}

private void CellComboBoxOnelectionChangeCommitted(object sender, EventArgs e)
{ 
    DataGridViewComboBoxEditingControl comboBox = sender as DataGridViewComboBoxEditingControl;
    if (sender == null)
    {
        return;
    }     
    if (comboBox.SelectedValue == null)
    {
        return;
    }    
    if (this.gridView.CurrentCell.Value == comboBox.SelectedValue)
    {
        return;
    }    
    this.gridView.CurrentCell.Value = comboBox.SelectedValue;        
}
like image 28
bitbonk Avatar answered Feb 28 '23 07:02

bitbonk