I am working on a Windows Forms application in which I have several ComboBox in different columns of a DataGridView.
The need I have is to take the values in the event SelectedIndexChanged
of each control ComboBox, I have implemented the following code.
private void dgvDetCatalogo_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridViewTextBoxEditingControl dText = e.Control as DataGridViewTextBoxEditingControl;
if (dText != null)
{
dText.KeyDown -= new KeyEventHandler(dText_KeyDown);
dText.KeyDown += new KeyEventHandler(dText_KeyDown);
}
if (e.Control is ComboBox)
{
DataGridViewComboBoxEditingControl dgvCombo = e.Control as DataGridViewComboBoxEditingControl;
dgvCombo.SelectedIndexChanged -= new EventHandler(dgvCombo_SelectedIndexChanged);
dgvCombo.SelectedIndexChanged += new EventHandler(dgvCombo_SelectedIndexChanged);
}
}
private void dgvCombo_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox combo = sender as ComboBox;
if (combo != null)
{
if (dgvDetCatalogo.Columns[_index].Name == "colMedida")
{
_cboUnidadMedida = Convert.ToInt32(combo.SelectedValue);
MessageBox.Show($"_cboUnidadMedida: {_cboUnidadMedida}");
}
if (dgvDetCatalogo.Columns[_index].Name == "colImpuesto")
{
_cboImpuesto = Convert.ToInt32(combo.SelectedValue);
MessageBox.Show($"_cbolImpuesto: {_cboImpuesto}");
}
}
}
The index to put it to the Row I take it from this event.
private void dgvDetCatalogo_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dgvDetCatalogo.CurrentRow == null)
return;
_index = dgvDetCatalogo.CurrentRow.Index;
}
The _index variable is declared at the form level to be able to put it in row
of the event SelectedIndexChanged
The problem that I noticed when I select another element of the ComboBox is that it does not take it if at the time of changing the element I do not press the ENTER or TAB key
Not knowing how to control that, I think the solution is to take the values of the combox in the event SelectedIndexChanged
if there is another way that when you select any element of the combos the item change is confirmed.
The problem I have now is that when I select another combo from the same column or another combo from another column it gives me the following error, it deletes everything that was in that cell until the combo disappears.
The intention of what is implemented in the event SelectedIndexChanged
is that I try to get the id of what I select in each ComboBox and then use it in another place. The problem is that it does not enter any condition If
where I have the name of each column that is of type ComboBox, what is what I'm doing wrong?
Greetings!