I have a combobox named cmbSubjects. It’s purpose in my project is to change the subject in a quiz competition. I want it that when its selected item is changed, a message box should ask the quiz master to confirm if they will like to continue if there are unanswered questions on the subject in the combobox before the change. If they answer NO, the combobox should select its previously selected item. I got this code to do it but the problem is the messagebox appears twice if the quix master chooses NO on the messagebox. I found out the reason (after stepping into the code from a breakpoint) was that when the messagebox returns NO, my code changes the selected value of the combobox to its previous value, which triggers the cmbSubjects_SelectedIndexChanged event. I tried modifying the code by adding a variable to count the number of times the messagebox has appeared to prevent it. The problem is that it only appears after the combobox’s value is first changed. The code below is actually the modified one. Can anyone help me with this? Thanks in advance. (I’m using C#)
private void cmbSubjects_SelectedIndexChanged(object sender, EventArgs e)
{
if (pnlAvailable.Controls.Count != 0)
{
if (countMsg < 1)
{
DialogResult res = MessageBox.Show("There are still available questions. Are you sure you want to change the subject?", "Changing subject...", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
if (res == DialogResult.Yes)
{
cmbIndex = cmbSubjects.SelectedIndex;
countMsg = 0;
switch (cmbSubjects.SelectedIndex)
{
case 0:
subject = "life";
break;
case 1:
subject = "math";
break;
case 2:
subject = "physical";
break;
case 3:
subject = "technology";
break;
case 4:
subject = "vocational";
break;
}
GenQstBtns();
}
else if (res == DialogResult.No)
{
countMsg = 1;
cmbSubjects.SelectedIndex = cmbIndex;
}
}
}
}
You can use SelectionChangeCommitted event.
So if you use this event after you change selected item programmatically this event wont be fired again