【问题标题】:C# Windows Forms how to change values of second combo box based on selection in first combo boxC# Windows 窗体如何根据第一个组合框中的选择更改第二个组合框的值
【发布时间】:2015-06-19 10:43:50
【问题描述】:

我正在尝试创建一个订单表单,因此我正在使用组合框来让用户选择要订购的商品。因此,当用户选择要订购的商品时,第二个组合框应该更改为可以订购特定商品的尺寸。我已经用所有商品的尺寸填充了第二个组合框,但我是不确定如何限制每个所选项目的大小。我曾尝试使用 if 语句将范围添加到第二个组合框,但这只会复制组合框末尾的项目。对此可以提供的任何帮助将不胜感激。谢谢

   private void itemBox_SelectedIndexChanged(object sender, EventArgs e)
   {
        switch (((ComboBox)sender).SelectedItem as string)
        {
            case "Name in a Frame":
                sizeBox.SelectedIndex = 0;
                break;
            case "Scrabble Frame":
                sizeBox.SelectedIndex = 1;
                break;
            case "Plaque":
                sizeBox.SelectedIndex = 2;
                break;
            case "Hearts":
                sizeBox.SelectedIndex = 3;
                break;
            case "Now and Forever Print":
                sizeBox.SelectedIndex = 4;
                break;
            case "Pat cushion":
                sizeBox.SelectedIndex = 5;
                break;
            case "Emilia cushion":
                sizeBox.SelectedIndex = 6;
                break;
        }
    }

    private void sizeBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (sizeBox.SelectedIndex == 0)
        {
            this.sizeBox.Items.AddRange(new object[]{
                "7x5",
                "10x8",
                "A4",
                "Mug"
            });
        }
    }

【问题讨论】:

    标签: c# winforms combobox


    【解决方案1】:

    您可以直接从 itemBox 选择的更改事件处理程序中填充 sizeBox 集合并完全删除 sizeBox_SelectedIndexChanged

    但是,要实现什么,您需要在选择项目后清除 sizeBox 中的项目。您可以通过以下方式实现:

    sizeBox.Items.Clear();
    

    一旦 sizeBox 选择的索引发生变化,您就可以添加项目。我会简单地使用:

    sizeBox.Items.Add("New Size");
    

    为了获得良好的实践,我会删除魔术字符串的使用,也许将它们放在返回适当字符串的 Products 帮助器类中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      相关资源
      最近更新 更多