Search code examples
c#winformscombobox

How to update the values in a combobox triggered by another combobox?


I have 2 comboboxes in a form.

I'd like the selected value in combobox1 to change when the list in combobox2 gets updated.

For Example: ComboBox1 has names of mobile companies and ComboBox2 containing the list of all mobile phones of that company.


Solution

  • Assume you have a dictionary that associates phone models to their manufacturers:

    Dictionary<string, string[]> brandsAndModels = new Dictionary<string, string[]>();
    
    public void Form_Load(object sender, EventArgs e)
    {
        brandsAndModels["Samsung"] = new string[] { "Galaxy S", "Galaxy SII", "Galaxy SIII" };
        brandsAndModels["HTC"] = new string[] { "Hero", "Desire HD" };
    }
    

    You can get the items to be displayed in the left combo box as:

    foreach (string brand in brandsAndModels.Keys)
        comboBox1.Items.Add(brand);
    

    You do this only once, for example in the form's Load event. Note: The brandsAndModels dictionary must be an instance variable, not a local variable as we need to access it later on.

    Then, you'd have to assign an event handler for the SelectedIndexChanged event, in which you replace the items in the second combo box with the items in the array for the selected brand:

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        comboBox2.Items.Clear();
    
        if (comboBox1.SelectedIndex > -1)
        {
            string brand = brandsAndModels.Keys.ElementAt(comboBox1.SelectedIndex);
            comboBox2.Items.AddRange(brandsAndModels[brand]);
        }
    }
    

    If all of this came from a database, things would be much nicer using data bindings as described in the answers to the question I've linked in my comment to your question.