Darw1n34
Darw1n34

Reputation: 332

Combobox contents based on another combobox value

I have two comboboxes where the first one has categories (and I can fill that easily from the source file). The trick is having the second combobox show only the items that are associated with the chosen category from the first combobox. For example:

cb1 is populated from a sourcefile with the category values 1, 2, 3 & 4 and cb2 is populated with values A,B,C,D,E,F,G,H

What I am failing at doing is limiting what is seen in cb2. So when cb1's value is "1", I only want "A" and "B" to be visible in cb2, and if cb1 changes to "2" I only want "C" and "D" to be visible.

Upvotes: 0

Views: 3622

Answers (1)

Christopher Townsend
Christopher Townsend

Reputation: 1746

For winforms :

If you have a form with 2 combo boxes (cb1, cb2) you could use something like this? (obviously modified to support your data objects).

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //create a list for data items
            List<MyComboBoxItem> cb1Items = new List<MyComboBoxItem>();

            //assign sub items
            cb1Items.Add(new MyComboBoxItem("1")
            {
                SubItems = { new MyComboBoxItem("A"), new MyComboBoxItem("B") }
            });

            cb1Items.Add(new MyComboBoxItem("2")
            {
                SubItems = { new MyComboBoxItem("C"), new MyComboBoxItem("D") }
            });

            cb1Items.Add(new MyComboBoxItem("3")
            {
                SubItems = { new MyComboBoxItem("E"), new MyComboBoxItem("F") }
            });

            cb1Items.Add(new MyComboBoxItem("4")
            {
                SubItems = { new MyComboBoxItem("G"), new MyComboBoxItem("H") }
            });

            //load data items into combobox 1
            cb1.Items.AddRange(cb1Items.ToArray());
        }

        private void cb1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //get the combobox item
            MyComboBoxItem item = (sender as ComboBox).SelectedItem as MyComboBoxItem;

            //make sure no shinanigans are going on
            if (item == null)
                return;

            //clear out combobox 2
            cb2.Items.Clear();

            //add sub items
            cb2.Items.AddRange(item.SubItems.ToArray());
        }
    }

    public class MyComboBoxItem
    {
        public string Name;
        public List<MyComboBoxItem> SubItems = new List<MyComboBoxItem>();

        public MyComboBoxItem(string name)
        {
            this.Name = name;
        }

        public override string ToString()
        {
            return Name;
        }
    }

Upvotes: 2

Related Questions