繁体   English   中英

填充时如何防止ComboBox触发另一个ComboBox的SelectedIndexChanged事件

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

因此,基本上,我正在使用ComboBox.SelectedIndexChanged事件来填充5个以上的ComboBox每个ComboBox都具有自己的SelectedIndexChanged事件。

问题在于,当第一个SelectedIndexChanged事件触发以填充其余事件时,它还会触发另一个ComboBoxSelectedIndexChanged事件。

为了防止这种情况,我在其余的ComboBox上找到了使用事件SelectionChangeCommited的解决方案。

但是现在,该事件(与SelectedIndexChanged不同)不会在ComboBox的第一次单击时触发……您需要先选择该项目两次或三次。

所以,我的问题是:有什么办法可以解决这些问题?

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

我将创建局部变量并将其设置为应该忽略SelectedIndexChanged的时间

protected bool ignoreSelectedIndexChanged = false;

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

    //rest of code
}

在我看来,比摆弄这些事件更为明确。

在主ComboBox使用类似以下内容的内容:

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

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

    }
    finally
    {
        ignoreSelectedIndexChanged = false;
    }
}

SelectionChangedCommited可能是另一种方法。 但是只有在用户进行选择时才会触发,这在某些情况下可能会受到限制。 而且还有一些圆顶虫,它们不应该在什么时候发射。 我个人避免这样做。

例如,使用标志
万一只有两个组合框

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;
    }        
}

就像这样,取决于您使用的组合框的数量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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