I have a datagrid with a combobox, i want to get my value, i can get it but i dont know why, i get it 4 times ??? could someone help me ?
here my code :
private void dgvLocataire_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
dgvLocataire.BeginEdit(false);
var ec = dgvLocataire.EditingControl as DataGridViewComboBoxEditingControl;
if (ec != null && ec.Width - e.X < SystemInformation.VerticalScrollBarWidth)
ec.DroppedDown = true;
if ((e.ColumnIndex != 3) && (e.ColumnIndex != 4))
{
dgvLocataire.Columns[e.ColumnIndex].ReadOnly = true;
}
dgvLocataire.CellValueChanged +=
new DataGridViewCellEventHandler(dgvLocataire_CellValueChanged);
//dgvLocataire.CurrentCellDirtyStateChanged +=
//new EventHandler(dgvLocataire_CurrentCellDirtyStateChanged);
}
private void dgvLocataire_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
dgvLocataire.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void dgvLocataire_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
string comboboxSelectedValue = string.Empty;
if (dgvLocataire.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewComboBoxColumn))
comboboxSelectedValue = dgvLocataire.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
MessageBox.Show(comboboxSelectedValue);
}
The messagebox appears 4 times when i choose a value in combobox. Thanks for your help
In dgvLocataire_CellMouseClick method, you are subscribing to dgvLocataire_CellValueChanged every time you click. Which means it can be called multiple times => MessageBox.Show(comboboxSelectedValue) is called multiple times.
You should subscribe to this event only once at the initialization of this form.