Click here to Skip to main content
15,901,001 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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.


XML
foreach (var comboBox in panel2.Controls.OfType<ComboBox>())
{
    comboBox.DataSource = ds.Tables[1];
    comboBox.DisplayMember = "FeeName";
    comboBox.ValueMember = "ID";
}
Posted
Comments
ZurdoDev 21-Mar-14 15:45pm    
That means you wired them all up to the same event.

Try this:
C#
foreach (var comboBox in panel2.Controls.OfType<ComboBox>())
{
    comboBox.DataSource = ds.Tables[1].Copy();
    comboBox.DisplayMember = "FeeName";
    comboBox.ValueMember = "ID";
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 21-Mar-14 18:18pm    
My 5, but I added a different variant of the loop and explained why it's a bit better, in certain aspect — Solution 2.
—SA
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:
C#
foreach(Control control in panel2.Controls) {
    ComboBox comboBox = control as ComboBox;
    if (comboBox == null) continue;
    comboBox.//... dereference if and do the same thing
    //...
}

—SA
 
Share this answer
 
Maybe solution is to add some kind of flag to the form? Make private field like:

C#
private bool isUpdating = false;


In your code responsible for updating comboboxes do some kind of trick:
C#
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;
}


And then in SelectedIndexChanged of every combobox (or if shared event handler) insert IF statement:
C#
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (!isUpdating)
    {
        // Real code goes here
    }
}


Consider setting SelectedIndexItem to -1 after updating ComboBoxes datasources.

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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900