2

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!

3 Answers3

1

You would need to define the OnSelectionChanged Event of the comboBoxes.

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
1

you can try

listBox1_SelectedIndexChanged(obj ... , sender e)
{
     if(listBox1.SelectedItem.ToString() == "Fruit")
     {
        listBox2.Items.Add("Orange");
        listBox2.Items.Add("Apple");
      }
     else if()
     {
        // other conditons
      }
}

listBox2_SelectedIndexChanged(obj ... , sender e)
{
     if(listBox2.SelectedItem.ToString() == "Apple")
     {
        listBox3.Items.Add("Red");
        listBox3.Items.Add("Green ");
      ........
      }
     else if()
     {
        // other conditons
      }
}

read http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selectedindexchanged.aspx

anishMarokey
  • 11,279
  • 2
  • 34
  • 47
1

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.

Ahmed
  • 645
  • 4
  • 13
  • 24