简体   繁体   中英

How to prevent a ComboBox from firing another ComboBox's SelectedIndexChanged event when filling it

So, basically I'm using a ComboBox.SelectedIndexChanged event to fill 5 more ComboBox s wich each have their own SelectedIndexChanged event as well.

The problem is that when the first SelectedIndexChanged event fires to fill the rest.. it also fires the other ComboBox es' SelectedIndexChanged event.

In order to prevent that, I have found a solution using the event SelectionChangeCommited on the rest of the ComboBox es.

But now, that event (unlike SelectedIndexChanged ) doesn't fire on the first click on the item of the ComboBox ... you need to select the item two or three times before it does.

So, my question is: is there any way to fix these problems?

在代码中,“填充”辅助组合框之前,请取消订阅其SelectedIndexChanged事件,然后在运行“填充”代码时重新订阅

I would make local variable and set it for the time the SelectedIndexChanged should be ignored

protected bool ignoreSelectedIndexChanged = false;

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ignoreSelectedIndexChanged) { return; }

    //rest of code
}

it seems to me more explicit than fiddling with the events.

In the main ComboBox use something like:

private void comboBoxMain_SelectedIndexChanged(object sender, EventArgs e)
{            
    try
    {
        ignoreSelectedIndexChanged = true;

        //comboBox1.SelectedIndex = 1;
        //comboBox2.SelectedIndex = 2;
        //comboBox3.SelectedIndex = 3;
        //...

    }
    finally
    {
        ignoreSelectedIndexChanged = false;
    }
}

SelectionChangedCommited may be another way how to do it. But it is fired only when user does the selection, what may be limiting for some cases. And there were dome bugs of not firing when it should. I personally avoid it.

Using a flag, for example
in case you only have 2 combo boxes

int flag =0;

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    switch(flag)
    {
       case 0:
           flag = 1;
       break;

       case 1:
           // your code here
           // after it you should set flag = 0
       break;

       default:
       break;
    }

}

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{

    switch(flag)
    {
       case 0:
           flag = 2;
       break;

       case 2:
           // your code here
           // after it you should set flag = 0
       break;

       default:
       break;
    }        
}

and just like that depending on the number of comboboxes you're using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM