C# – listBox selected item

cwinforms

I have three listBoxes:

listBox1 have the following items: Fruit and vegetable.

listBox2 have the following items: Orange, Apple, cucumber and Tomato.

listBox3 have the following items: Red, Green, Yellow and Orange.

And i want to do like this, if i select Fruit in listBox1 i only want to show Orange and Apple in listBox2 and if i select Apple in listBox2 i want to show Red, Green and Yellow for example.

And if nothing is selected in listBox1 then listBox2 and 3 shall be empty and if nothing is selected in listBox2 then listBox3 shall be empty.

And is there any good way to make a select/deselect method?

Thanks!

Best Answer

You can try something like this, for easy understanding divide the functionality into functions. I designed this code using win forms however you can apply same code on List boxes as well.

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch(comboBox1.SelectedItem.ToString())
        {
            case "Fruit":
                FruitSelected();
                break;
            case "Vegetables":
                VegetableSelected();
                break;
            default:
                NoneSelected();
                break;
        }
    }
    private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Similar code as above
    }
    protected void FruitSelected()
    {
        comboBox2.Items.Clear();
        comboBox2.Items.Add("Orange");
        comboBox2.Items.Add("Apple");
    }
    protected void VegetableSelected()
    {
        comboBox2.Items.Clear();
        comboBox2.Items.Add("Tomato");
        comboBox2.Items.Add("Cucumber");
    }
    protected void NoneSelected()
    {
        comboBox2.Items.Clear();
        comboBox3.Items.Clear();
    }
}

Hope it helps.

Related Topic