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.
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With