避免groupBox中所有组合框的SelectedIndexChanged函数在更改其中一个选项时被触发。 [英] Avoid SelectedIndexChanged function of all the comboboxes in a groupBox from getting fired while changing selection only for one of them.

查看:61
本文介绍了避免groupBox中所有组合框的SelectedIndexChanged函数在更改其中一个选项时被触发。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过使用DataSource属性和数据集中的相同数据来填充8个组合框,并为所有这些属性定义了SelectedIndexChanged函数。



现在我的问题是SelectedIndexChanged如果我改变我对任何组合框的选择,所有组合框的功能都会被触发。





I am filling 8 combobox by using their DataSource property with same data from dataset and have defined SelectedIndexChanged function for all of them.

Now my problem is that SelectedIndexChanged function of all the comboboxes get fired if I change my selection for any of the comboboxes.


foreach (var comboBox in panel2.Controls.OfType<ComboBox>())
{
    comboBox.DataSource = ds.Tables[1];
    comboBox.DisplayMember = "FeeName";
    comboBox.ValueMember = "ID";
}

推荐答案

试试这个:
foreach (var comboBox in panel2.Controls.OfType<ComboBox>())
{
    comboBox.DataSource = ds.Tables[1].Copy();
    comboBox.DisplayMember = "FeeName";
    comboBox.ValueMember = "ID";
}


除了解决方案1:



使用 OfType<> 方法看起来非常优雅,清晰,可读且可靠,但它在性能和内存使用方面并不是最好的,因为它创建了一个中间集合这个代码并不真正需要的对象。因此,更长的代码更实用:

In addition to Solution 1:

The use of the OfType<> method looks of course very elegant, is clear, readable and reliable, but it is not the best in terms of performance and memory usage, because it creates an intermediate collection object which is not really needed for this code. Therefore, a bit longer code is more practical:
foreach(Control control in panel2.Controls) {
    ComboBox comboBox = control as ComboBox;
    if (comboBox == null) continue;
    comboBox.//... dereference if and do the same thing
    //...
}



-SA


也许解决办法是在表单中添加某种标志?使私人领域如下:



Maybe solution is to add some kind of flag to the form? Make private field like:

private bool isUpdating = false;





在你负责更新组合框的代码中有一些技巧:



In your code responsible for updating comboboxes do some kind of trick:

private void UpdateDataSources()
{
    isUpdating = true;

    foreach (var comboBox in panel2.Controls.OfType<ComboBox>())
    {
        comboBox.DataSource = ds.Tables[1];
        comboBox.DisplayMember = "FeeName";
        comboBox.ValueMember = "ID";
    }

    isUpdating = false;
}





然后在每个组合框的SelectedIndexChanged中(或者如果共享事件处理程序)插入IF语句:



And then in SelectedIndexChanged of every combobox (or if shared event handler) insert IF statement:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (!isUpdating)
    {
        // Real code goes here
    }
}





在更新ComboBoxes数据源后,请考虑将SelectedIndexItem设置为-1。



我没试过这,但我认为这可以帮助你。让我知道:))



Consider setting SelectedIndexItem to -1 after updating ComboBoxes datasources.

I didn't tried this but i think that can help you. Let me know :)


这篇关于避免groupBox中所有组合框的SelectedIndexChanged函数在更改其中一个选项时被触发。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆