【问题标题】:listBox selected item列表框选定项
【发布时间】:2011-05-02 10:48:53
【问题描述】:

我有三个列表框:

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

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

listBox3 有以下项目:Red、Green、Yellow 和 Orange。

我想这样做,如果我在 listBox1 中选择水果,我只想在 listBox2 中显示橙色和苹果,如果我在 listBox2 中选择苹果,我想显示红色、绿色和黄色。

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

有没有什么好的方法来制作选择/取消选择方法?

谢谢!

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    您可以尝试这样的操作,以便于理解将功能划分为功能。我使用 win 表单设计了此代码,但是您也可以在列表框中应用相同的代码。

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

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      您需要定义组合框的OnSelectionChanged 事件。

      【讨论】:

        【解决方案3】:

        你可以试试

        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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-09-22
          • 1970-01-01
          • 2015-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-24
          相关资源
          最近更新 更多