【问题标题】:populate combobox1 depending to another combobox2 [closed]根据另一个组合框2填充组合框1 [关闭]
【发布时间】:2021-05-31 09:59:19
【问题描述】:

我想填充组合框2,但考虑到组合框1上选择的值; 例如,如果选择组合框 1 的值 1;自动组合框2将填充值“a”和“b”....

private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
    {        
        int selectedIndex = combobox1.SelectedIndex;


        if (selectedIndex == 1)
        {
            combobox1.Items.Clear();
            combobox1.Items.Add(" a");
            combobox1.Items.Add("b");            
        }

        else if (selectedIndex == 2)
        {
            combobox2.Items.Clear();
            combobox2.Items.Add("c");
            combobox2.Items.Add("d");           
        }
    }

显示此错误:

System.ArgumentOutOfRangeException:'InvalidArgument='0' 的值对'SelectedIndex' 无效。 参数名称:SelectedIndex'

如果有人有任何想法,他们可以帮助我们解决这个问题;谢谢

【问题讨论】:

标签: c# asp.net visual-studio winforms


【解决方案1】:

问题是组合框的项目索引从0开始。您需要进行以下更改:

 private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
{        
    int selectedIndex = combobox1.SelectedIndex;


    if (selectedIndex == 0) 
    {
        combobox1.Items.Clear();
        combobox1.Items.Add(" a");
        combobox1.Items.Add("b");            
    }

    else if (selectedIndex == 1)
    {
        combobox2.Items.Clear();
        combobox2.Items.Add("c");
        combobox2.Items.Add("d");           
    }
}
     

【讨论】:

  • 感谢它对我有用
  • @issam jallal,很高兴听到您的问题已经解决,您可以点击“✔”将有用的回复标记为答案。它还将帮助其他人解决类似的问题。
【解决方案2】:

根据我的测试,您可以尝试以下代码,根据当前组合框填充另一个组合框。

另外,如果你需要使用过多的if语句,我建议你可以试试switch..case语句。

 private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("test1");
            comboBox1.Items.Add("test2");
            comboBox1.Items.Add("test3");
            comboBox1.Items.Add("test4");

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = comboBox1.SelectedIndex;
            comboBox2.Items.Clear();
            switch (index)
            {
                case 0:
                    comboBox2.Items.Add("a");
                    comboBox2.Items.Add("b");
                    break;
                case 1:
                    comboBox2.Items.Add("c");
                    comboBox2.Items.Add("d");
                    break;
                case 2:
                    comboBox2.Items.Add("e");
                    comboBox2.Items.Add("f");
                    break;
                case 3:
                    comboBox2.Items.Add("g");
                    comboBox2.Items.Add("h");
                    break;
                default:
                    MessageBox.Show("Wrong Index");
                    break;
            }
        }

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多