listBox选中的项目

我有三个listBoxes:

listBox1有以下几项:水果和蔬菜。

listBox2有以下几项:橙子,苹果,黄瓜和番茄。

listBox3具有以下项目:红色,绿色,黄色和橙色。

我想这样做,如果我在listBox1中选择Fruit我只想在listBox2中显示Orange和Apple,如果我在listBox2中选择Apple,我想显示红色,绿色和黄色。

如果在listBox1中没有选择任何内容,则listBox2和3应为空,如果在listBox2中没有选择任何内容,则listBox3应为空。

是否有任何好的方法来制作选择/取消选择方法?

谢谢!

您可以尝试这样的事情,以便于理解将function划分为function。 我使用win表单设计了此代码,但您也可以在List框中应用相同的代码。

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(); } } 

希望能帮助到你。

您需要定义combobox的OnSelectionChanged事件。

你可以试试

 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 } } 

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